Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect the global reference in javascript

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 :-|

like image 840
ShrekOverflow Avatar asked Nov 25 '13 21:11

ShrekOverflow


1 Answers

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
        })();
 };
like image 197
PSL Avatar answered Sep 28 '22 08:09

PSL