The following 2 snippets give same result. I wondered what is the real diffence in these 2 approaches and when should one be used instead of another way. Can someone help me out understanding the difference?
Case 1:
class Person{
constructor(name){
this.name = name;
}
printData(){
console.log(this.name);
}
}
Case 2 :
class Person{
constructor(name){
this.name = name;
this.printData = function(){
console.log(this.name);
}
}
}
The different is instance property versus prototype.
When you define a function inside the constructor, each new instance gets a new function defined, akin to
{
printData: function () { ... }
}
When you define the method in the class, it is defined in the prototype and shared by every instance.
i.e. with first approach,
const p1 = new Person('bob')
const p2 = new Person('rob')
p1.printData === p2.printData // false
with second approach
const p1 = new Person('bob')
const p2 = new Person('rob')
p1.printData === p2.printData // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With