Question

The following javascript code, allows you to access the global object (window/worker).

(new function Outer(){
    console.log(this); /* The object */
    (function(){ // This function could be a 3rd Party function 
        console.log(this); /* window !!*/
    })();
});

Is there a way by which I can ensure that the inner this always gets a reference to Outer's context.

I know i can do

(new function Outer(){
    'use strict';
    console.log(this); /* The object */
    (function(){ // This function could be a 3rd Party function 
        console.log(this); /* undefined ? !!*/
    })();
});

but that results in this being undefined.

Edit

I know about bind, but what if the inner function is nested. for instance something like

(function(){

    (function(){
        (function(){
           console.log(this);// undefined
        })();

    })();

}).bind(this)();

What i want is : Outer {} and not a reference to the outer using a variable :-|

Was it helpful?

Solution

You can use function.call.

new function Outer(){
    'use strict';
    console.log(this); 
    (function(){ // This function could be a 3rd Party function 
        console.log(this);  //<-- Now it will it the one from the outer scope
    }).call(this);
}; // You don't need to invoke this explicitly here with () since you are invoking it already with new keyword so constructor invocation doesnt need ()

Or a best bet would be to cache the context outside and use it anywhere in the inner scope.

new function Outer(){
        'use strict';
        var self = this;
        console.log(this); 
        (function(){ // This function could be a 3rd Party function 
            console.log(self);  //<-- Now it will it the one from the outer scope
        })();
 };

OTHER TIPS

You can use a closure variable:

(new function Outer(){
    'use strict';
    console.log(this);
    var me = this;
    (function(){
        console.log(me);
    })();
})();

This trick simply stores the "outer" this inside a variable that you can access from inner functions (and inner-inner function and so on).

In some cases, this can be useful because you have access to both the inner this (if there is a context for it) and the outer this.

(new function Outer(){
    'use strict';
    console.log(this); /* The object */
    var _this = this;
    (function(){ // This function could be a 3rd Party function 
        console.log(_this); /* The outer object */
    })();
})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top