th3Jay
th3Jay

Reputation: 9

Javascript: Reference Variable

    var foo = {
    _name: 'John',
    getIdentity: function (){
        return this._name;
    }
};

var stoleIdentity = foo.getIdentity;

console.log(stoleIdentity());
console.log(foo.getIdentity());

Hi, may I know, is there any other implementation for me to achieve the same result as the code above?

And why I cannot get the result for the stoleIdentity?

Upvotes: -1

Views: 88

Answers (2)

Kevin
Kevin

Reputation: 1319

When you assigned foo.getIdentity to stoleIdentity, the this was changed. You can log this to check it out.

Use this bind to bind this to stoleIdentity to let it work.

var foo = {
    _name: 'John',
    getIdentity: function (){
        return this._name;
    }
};

var stoleIdentity = foo.getIdentity.bind(foo);

console.log(stoleIdentity());
console.log(foo.getIdentity());

Upvotes: -1

Amadan
Amadan

Reputation: 198304

this in JavaScript gets defined by very specific circumstances; the one we're interested in is in a "method call", which looks like this:

receiver.method(argument_list...)

If the receiver is not mentioned in the function call, it is a plain function call, not a method call, and this does not get set.

Thus, foo.getIdentity() is a method call, which sets this to foo, and this._name gets evaluated as foo._name; stoleIdentity() is a plain function call, which does not change this, and this._name will likely access window._name, unless this got changed some other way in the meantime.

You can bind the receiver to a function value using Function.prototype.bind (one of the other ways to change this). So if you use this line instead, your code will work:

var stoleIdentity = foo.getIdentity.bind(foo);

Upvotes: 2

Related Questions