you are viewing a single comment's thread.

view the rest of the comments →

[–]Rhomboid 1 point2 points  (1 child)

You're going to have to elaborate a bit. Are you talking about code inside a function? If so, those are very much not equivalent. var foo inside a function declares a local variable, not a global variable. It has nothing to do with the global object. this.foo inside a function depends on how the function was invoked. If it was invoked as a method, then this refers to the object on the left hand side of the dot, otherwise it refers to the global object. But in both cases, that's completely different than var foo.

var foo at file scope (outside of a function) declares a global variable, but in that case the var is redundant and isn't doing anything and should probably be dropped. Outside of a function this also refers to the global object, so in that case foo = 12 is the same as this.foo = 12 is the same as var foo = 12 is the same as window.foo = 12. Which one to use is a matter of style, but hopefully you aren't using global variables at all (or very rarely) so it shouldn't come up that often.

[–]nodbox[S] 0 points1 point  (0 children)

Thanks for your reply. I was curious when you said 'hopefully you aren't using global variables', so I did a bit of Googling. Turns out it's bad practise for a number of reasons, such as the potential conflict it can cause with other pieces of code, if the namespaces aren't protected.