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.