0

Given following code:

var User = function(name) {
    this.name = name;
};

User.prototype.sayHello = function() {
    console.log('Hi my name is ' + this.name + '.');
};

var user1 = new User('Bob');
user1.sayHello();

What i learned so far is that the this keyword when used in function statements points at the global object, and when used in methods, at the object it lexically sits in.

I also know that the new keyword creates an empty object and calls the constructor and letting it point to that new object.

But what I dont understand is, since user1 doesn't own the sayHello function, it goes up the prototype chain. But how does the function in the prototype know where to refer with this.name?

The output in the console is: Hi my name is Bob.

veteri
  • 79
  • 7
  • perhaps https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain will educate you – Jaromanda X Apr 07 '17 at 10:06
  • The new keyword not only creates a new object, it also 'automatically' 'binds' the prototype to that new object, so although user1 itsself didn't define that method, it's still a method of user1. The first step in the prototype chain of user1 instance is User.prototype and the prototype methods will use the instance they are called upon as their this value. – Shilly Apr 07 '17 at 10:18

1 Answers1

0

Because its created from User object if you do an console.log on user1.name you will get Bob as output next sayHello is called with reference to user1 so this.name resolves to Bob

var User = function(name) {
    this.name = name;
};

User.prototype.sayHello = function() {
    console.log('Hi my name is ' + this.name + '.');
};

var user1 = new User('Bob');
console.log(user1.name)
user1.sayHello();
Vinod Louis
  • 4,659
  • 1
  • 19
  • 41