javascript - How does a prototype function know where to point when using 'this'? -
this question has answer here:
- how “this” keyword work? 19 answers
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
Post a Comment