关于子类修改prototype里的函数
来源:2-16 Sub Classes(如何继承一个类?)

owenhan
2020-05-09
这个问题在学习这一章内容后困扰了比较久,代码如下:
class Animal {
constructor(type) {
this.type = type
}
eat() {
console.log('Animal eat');
}
}
class Dog extends Animal {
}
const dog1 = new Dog();
const dog2 = new Dog();
const bird = new Animal();
dog1.constructor.prototype.eat = function () {
console.log("changed");
}
dog1.eat();
dog2.eat();
bird.eat();
输出结果:
changed
changed
Animal eat
理论上子类修改的是原型链中的函数,原型链中的函数是来自父类,他们之间是共享的。
为何子类修改了原型链上的函数,修改后的函数只在子类的实例间体现出来了,在父类的实例没有起到效果呢?
写回答
1回答
-
慕粉1926294646
2020-05-11
dog1.constructor === Dog 不等于 Animal
00
相似问题