I am really confused as to why sometimes vars will not work when “var” is declared in front of them when used in a namespaced object. Isn’t adding “var” in front of every variable the correct thing to do to keep it outside the global namespace?
Or would creating any var without declaring “var” first in my namespaced object, ensure of this, so I don’t eed to worry about “var”?
Here’s an example of my code:
MYNAME.DoStuff = {
initialize: function() {
var var1 = 'name'; //1
var2 = 'name'; //2
this.var3 = 'name'; //3
var $var4 = $('#' + name); //4
$var5 = $('#' + name); //5
this.$var6 = $('#' + name); //6
},
linkStuff: function() {
// then use the vars from the init above in here
}
}
MYNAME.DoStuff.initialize();
Can someone tell me which number (1, 2, or 3) is correct? Are there cases where I would use more than one or all? How about when I need to do DOM references with jQuery? Which way is correct (4, 5, or 6)?
The
varstatement will bind the variable to the scope of the current function, in your examplevar1is accessible only withininitialize.Your second example,
var2 = 'name';is simply an assignment made to a -possibly- undeclared identifier.This is an anti-pattern, and should be avoided. If the identifier is not resolvable higher in the scope chain,
var2will end up being a property of the global object -an implied global, since most of the time you actually try to avoid globals-.Moreover, the new ECMAScript 5 Strict Mode, completely disallows this kind of assignments, please avoid them…
The third example,
this.var3will create a property in the current object, in your example thethisvalue ofinitializewill refer toMYNAME.DoStuffbecause you invoke the initialize method byMYNAME.DoStuff.initialize();.In this third example you can access this kind of properties on your
linkStufffunction, just bythis.var3– if you invoke thatlinkStufffunction properly, e.g.MYNAME.DoStuff.linkStuff();-.