Reputation: 11468
I want to create a static variable in my js. From what I know with my little js knowledge is, I can do it using this two ways.
function foo (){
if (this.counter==undefined){this.counter=1}
else {this.counter++ } ;
}
function foo (){
if (foo.counter==undefined){foo.counter=1}
else {foo.counter++ } ;
}
Are these two things essentially the same or I need to to careful in selecting one versus other.
Another question I have is: why var is not needed when doing these?
Upvotes: 0
Views: 56
Reputation: 41832
No, they are not equivalent. In your first example, you are using this
. this
can actually change depending on how the function is being called.
function showThis(){
console.log(this);
}
var obj = { };
obj.showThis = showThis;
showThis(); // gives 'window', or the top-most scope of your page
obj.showThis(); // gives obj as 'this'
If you are always calling the function the same way, then this would just mean the value counter
is tracked as a property on window.counter
. This is bad, because you may accidentally have an actual variable named counter
in that scope, that you are now using in a different way somewhere else. If you are not calling it the same way everytime, then this
will be different and probably not giving you your desired behavior.
If you are trying to keep a count on the number of times foo
is being called, independent of how/who is calling it, then your second approach is more appropriate. For the sake of code clarify/convention, I would write it this way:
function foo (){
// If counter does not exist, create it and initialize it to 0.
foo.counter = foo.counter || 0;
foo.counter++;
}
foo.counter; // undefined, since foo has never been called yet
foo();
foo.counter; // is now 1
Upvotes: 2
Reputation: 943556
var
is used to create a variable in the current scope.
Both the approaches you are taking are setting a property on an object that exists in a wider scope.
Upvotes: 1