35.0k views
4 votes
What will the following code output to the console and why:

var hero = {
_name: 'John Doe',
getSecretIdentity: function (){
return this._name;
}
};

var stoleSecretIdentity = hero.getSecretIdentity;

(stoleSecretIdentity());
(hero.getSecretIdentity());
What is the issue with this code and how can it be fixed.

User Large
by
7.5k points

2 Answers

5 votes

Final answer:

The code outputs undefined and 'John Doe' due to how 'this' is handled in JavaScript. The method 'stoleSecretIdentity' loses its context when detached from the 'hero' object. Using '.bind(hero)' resolves the context issue, making both method calls output 'John Doe'.

Step-by-step explanation:

The code provided will output undefined when stoleSecretIdentity() is called and 'John Doe' when hero.getSecretIdentity() is called. The issue with the code is related to JavaScript's handling of this keyword in different contexts.

In the case of stoleSecretIdentity(), the context is global, hence this does not refer to the hero object anymore but to the global object, which does not have an _name property.

To fix this, you can explicitly bind stoleSecretIdentity to hero using the bind method like so: var stoleSecretIdentity = hero.getSecretIdentity.bind(hero);. After this change, both (stoleSecretIdentity()); and (hero.getSecretIdentity()); will output 'John Doe'.

User Simon Scarfe
by
9.2k points
5 votes

Final answer:

The code outputs undefined and 'John Doe' due to how 'this' is handled in JavaScript. The method 'stoleSecretIdentity' loses its context when detached from the 'hero' object. Using '.bind(hero)' resolves the context issue, making both method calls output 'John Doe'.

Step-by-step explanation:

The code provided will output undefined when stoleSecretIdentity() is called and 'John Doe' when hero.getSecretIdentity() is called. The issue with the code is related to JavaScript's handling of this keyword in different contexts. In the case of stoleSecretIdentity(), the context is global, hence this does not refer to the hero object anymore but to the global object, which does not have an _name property.



To fix this, you can explicitly bind stoleSecretIdentity to hero using the bind method like so: var stoleSecretIdentity = hero.getSecretIdentity.bind(hero);. After this change, both (stoleSecretIdentity()); and (hero.getSecretIdentity()); will output 'John Doe'.

User Hmofrad
by
7.7k points