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
foo.countermakes the variablecounteravailable from anyfooobject. (e.g.var a = new Foo(); var b = new Foo(); a.counter === b.counter;. I am not sure if that is the case with javascript too.footo create objects usingnewor just calling it as a function without thenew?thiskeyword. You will soon realize that this is not what you want.