I am trying to understand why an inner function can access a public property of an outer function when the outer function is called directly, but not when it is assigned to a variable?
Example:
function outer(x,y){
this.x = x;
this.y = y;
function inner(){
alert(this.x);
}
inner();
}
outer(1,2); //As expected, alerts 1
var func = outer(1,2) //Also alert 1
var func2 = new outer(1,2); //Alerts undefined
One thing I tried was to remove the this keyword from alert(this.x); and it did work for all three cases. However, if I do remove the this keyword, I’d be accessing the passed in param, not the public variable, which is definitely not the desired action. Can someone explain this behavior?
When you call
outer(1, 2)like that,thisis a reference towindow, so “x” and “y” are effectively global variables. That’s whyinner()can access “x”.When you call
new outer(1, 2)you have causedthis(in “outer”) to be a reference to a new object. When “inner” is called inside “outer”,thiswill still referencewindow, so there’s no “x”.The value of
thisis determined for every function call, and the value depends only on the particulars of that call. Thus the fact that you call “outer” vianewhas no effect on the interior call to “inner” — because you simply call the function asinner();, the value ofthisinside that function will be a reference towindow(well, the global context, whatever that is).Here are the ways
thiscan be set upon a call to a function:newoperator, thenthiswill refer to a newly-created object.foo.someFunction()), thenthiswill be a reference to that object..call()or.apply()from the Function prototype, thenthiswill refer to the first argument to whichever of those functions was used, coerced to an object value if necessary.thiswill refer to the global context (windowin a browser). edit — Šime Vidas points out in a comment above that in strict mode, this case results inthisbeingnull(which really makes a little more sense, and would avoid the weirdness observed in the OP).