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 );
}
}
If you use the Prototype library you could use Function#bind() like this:
var myObject = {
id: 1,
printId: function() {
var myId = function() {
return this.id;
}.bind(this);
console.log(myId());
}
}
A little overkill perhaps, but if you're using objects like this extensively it might be worth looking up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With