Q:

this.variable vs variable child scope

I have some JS code where I want to return my global object's instance in its child method (think fluent interface):
myGlobalVar = function() {
    this.self = this;
    this.Whatever = function() {
        //return self; // why does that FAIL??
        return this.self; // why does that WORK??
    }
}

I would have assumed that I'd return self but that fails. return this.self succeeds but I figured this in the child function would refer to said function. Why does this work?

A:

In javascript the value of this in a function is determined by the caller of the function.
When you call obj.method(), the value of this is set to obj inside of method().  So, in your example above, when you call myGlobalVar.Whatever(), the value of this inside of Whatever() will be myGlobalVar so to reference sefl, you use this.self as you have discovered.
self all by itself does not work because it is not a variable in the current scope all by itself.  It's a property of myGlobalVar and thus can ONLY be referenced as either myGlobalVar.self or this.self when this === myGlobalVar.  Javascript does not automatically check properties on the current object in order to resolve a symbol.  You can only reach a property of an object by specifically referencing the object that hosts the property as in this.self.

There are other ways that the value of this can be altered.  If Whatever() is called without the obj context such as:
var fn = myGlobalVar.Whatever;
fn();

Then, the value of this will be either the global object in regular JS or undefined in JS strict mode.

There are also .call() and .apply() methods on every function that allow you to directly specify what you want the this value to be set to inside the method as in myGlobalVar.Whatever.call(myOtherGlobalVar).

