Is it possible to extract a functions caller scope?
I have this example:
var myObject = {
id: 1,
printId: function() {
var myId = function() {
return this.id;
}
console.log(myId());
}
}
myObject.printId(); // prints 'undefined'
The example above prints out undefined
, because 'this' seems to be the window scope by default inside new functions (in this case myId). Is there any way I can use a proxy that applies the correct scope before executing?
Something like this (fictive):
var execute = function( fn ) {
fn.apply(fn.caller.scope);
}
var myObject = {
id: 1,
printId: function() {
var myId = function() {
return this.id;
}
execute( myId );
}
}