Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get function caller scope

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 );
    }
}
like image 986
David Hellsing Avatar asked Nov 20 '25 09:11

David Hellsing


1 Answers

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.

like image 106
shuckster Avatar answered Nov 22 '25 00:11

shuckster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!