I was working on a project for a while, trying to figure out what I was doing wrong, when I finally narrowed “the bug” down to the fact that the below code doesn’t work as I expected:
function Alpha()
{
this.onion = 'onion';
function Beta()
{
alert(this.onion);
}
Beta();
}
alpha1 = new Alpha();
// Alerts 'undefined'
However, if I change the code to this:
function Alpha()
{
var self = this;
this.onion = 'onion';
function Beta()
{
alert(self.onion);
}
Beta();
}
alpha1 = new Alpha();
// Alerts 'onion'
it works like I would expect. After wasting a large portion of my life, can anyone explain why it works like this?
Works like this because each function has associated its own execution context.
However there are other ways to do it, for example:
Using
callorapplyto invoke the function:The new ECMAScript 5th Edition Standard, introduces a way to persist the function context, the
Function.prototype.bindmethod:We can say that the
Betafunction is bound, and no matter how you invoke it, itsthisvalue will be the intact.This method is not widely supported yet, currently only IE9pre3 includes it, but you can include an implementation to make it work now.
Now let me elaborate about how
thisworks:The
thisvalue exist on each execution context, and for Function Code is set implicitly when a function call is made, the value is determined depending how the reference if formed.In your example, when you invoke
Beta();, since it is not bound to any object, we can say that the reference has no base object, then, thethisvalue will refer to the global object.Other case happens when you invoke a function that is bound as a property of an object, for example:
As you can see, the reference being invoked
obj.bar();contains a base object, which isobj, and thethisvalue inside the invoked function will refer to it.Note: The reference type is an abstract concept, defined for language implementation purposes you can see the details in the spec.
A third case where the
thisvalue is set implicitly is when you use thenewoperator, it will refer to a newly created object that inherits from its constructor’s prototype: