29th Nov 2021, 6:36 AM
ACE
ACE - avatar
3 Respuestas
+ 2
Good question. The new keyword is creating new instance of Person, making it a class. The prototype property is used to define protypical method of the Person class. For simple explanation, I would like to redirect you to part four of this tutorial by Ryan Els: https://code.sololearn.com/WjUaueh5He54/?ref=app For in-depth understanding, read these articles featured by David Carroll: https://www.sololearn.com/post/45261/?ref=app
29th Nov 2021, 7:14 AM
Gordon
Gordon - avatar
+ 1
ACE You misunderstood. Person.show() is called even if it is defined in arrow method. You can trace function triggering by adding console.log, like this: https://code.sololearn.com/WyHi42W308LE/?ref=app A further investigation shows that the "this" is different. functions defined with "function" keyword is looking up the prototypical chain when called, it sees the class instance as "this". functions defined with arrow function looks at the environment when the function is defined, in this case, "this" is window. "this" is tricky with old syntax, that's why ES6 introduces the class keyword, it provides safer way to define things. (especially let, const, etc.)
30th Nov 2021, 2:18 PM
Gordon
Gordon - avatar
0
Gordon I tried using Person.prototype.show = function() { console.log(this.name); } and it worked, but it wont work for es6 function. i.e Person.prototype.show = () => { console.log(this.name); } whats the reason behind it?
29th Nov 2021, 7:26 AM
ACE
ACE - avatar