I recently read somewhere (I am really sorry I can’t provide the source) that you can use this.varname to access globals in replacement to window.varname to save 2 chars
var myVar = "global";
function myFunc() {
var myVar = "notGlobal";
alert( this.myVar ); //global
}
It seems to work, but I want to know if:
- it is safe to use in old browsers
- it is cross-browser compatible
- it will fail under some weird circumstances
I don’t think I’d do it, but it’s completely cross-browser compatible if
thisis referring to the global object (window). Whether it is will depend on how the function in question was called (at global scope,thisdoes indeed refer to the global object), and whether the code in question is in “strict mode” or not. (In strict mode,thisdoes not refer to the global object. Kudos and upvotes to Esailija for pointing that out.)In non-strict code:
So at global scope:
And similarly, if you have a function you call directly:
But, in JavaScript,
thisis set entirely by how a function is called. So we could callfoosettingthisto something else:Similarly:
So in conclusion, at global scope (not in any function call), yes,
thisis reliably pointing to the global object, and if you control how the function gets called and you call it without settingthisto anything else (viacallorapply, or by using it from an object property a’laobj.fabove), then, again, it will reliably refer to the global object. This is covered by sections 10.4.1 (Entering Global Code) and 10.4.3 (Entering Function Code) of the specification. This is how it’s been from the very beginning, I believe; certainly for the last 15 years, so you’re unlikely to find a non-compliant environment.More reading:
this