class Parent {
work = () => {
console.log('This is work() on the Parent class');
}
}
class Child extends Parent {
work() {
console.log("This is work() on the Child class ");
}
}
const kid = new Child();
kid.work();
为什么执行的是父类方法?如果父类改为非箭头函数,又是执行子类方法。
这玩意儿就是访问优先级问题吧,好像带继承的语言都有。刚好这个语言里 父类属性优先级高于子类方法
Source: https://stackoverflow.com/a/51401151/5958455
简而言之,work = () => {} 是在 constructor() 里给 this.work() 的一种简写,而被明确复制的对象属性优先级总是高于在类中定义的方法,所以 Parent 里给 this.work 赋值的箭头函数“覆盖”了 Child.prototype.work
父类的 work 方法是在 constructor 是挂在实例上的
子类的 work 方法是挂在 Child.prototype 上的
class Parent {
work = function () {
console.log('This is work() on the Parent class');
}
}
和箭头函数没有关系,这种写法会定义新的字段,优先级高于原型链上的字段
明白了,忘了=号的作用了。谢谢。