-1
    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?

0

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This should be the answer.
Thank you so much for your explanation. It helped me understand clearly.
-1

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.