I am new to JS, I am particularly confused by following code:
class One{
constructor(num){
this.num = num;
}
add(){
this.num += 1;
}
showInfo(){
this.add();
console.log(`The result is ${this.num}`);
}
}
class Ten extends One{
constructor(num){
super(num);
}
add(){
this.num += 10;
}
}
let t = new Ten(1);
t.showInfo();
// The result is 11
I thought the result should be 2, because showInfo is executed in One so add should be executed in One as well, furthermore, showInfo is only defined in One, but why is One.showInfo calling Ten.add instead of One.add?
I will be so glad if someone offer some explanation.
console.log(this)in yourshowInfo- you'd not be surprised anymore.TeninstanceTen's prototypaladdmethod shadows the one implemented byOne. If one wants to support the latter for anyTeninstance one needs to implement another (prototypal) method which does asuperdelegation ... e.g.addOne() { return super.add(); }. Then one can do e.g.const t = new Ten(1); t.add() /* 11 */; t.addOne() /* 12 */;