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 :-|
window, but you also don't wantundefined. Hate to break it to you, but those are the two defaults that will be used for functions that are invoked without any other indicator of thethisvalue.undefinedthis, but that's of little use today, and it's only for functions with the new syntax.