javascript - How does a prototype function know where to point when using 'this'? -


this question has answer here:

given following code:

var user = function(name) {     this.name = name; };  user.prototype.sayhello = function() {     console.log('hi name ' + this.name + '.'); };  var user1 = new user('bob'); user1.sayhello(); 

what learned far this keyword when used in function statements points @ global object, , when used in methods, @ object lexically sits in.

i know new keyword creates empty object , calls constructor , letting point new object.

but dont understand is, since user1 doesn't own sayhello function, goes prototype chain. how function in prototype know refer this.name?

the output in console is: hi name bob.

because created user object if console.log on user1.name bob output next sayhello called reference user1 this.name resolves bob

var user = function(name) {      this.name = name;  };    user.prototype.sayhello = function() {      console.log('hi name ' + this.name + '.');  };    var user1 = new user('bob');  console.log(user1.name)  user1.sayhello();


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -