stackoverflow 上看到一个问题,不是很理解。

2021-04-15 16:41:41 +08:00
 waiaan

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();

为什么执行的是父类方法?如果父类改为非箭头函数,又是执行子类方法。

1897 次点击
所在节点    JavaScript
5 条回复
paddistone
2021-04-15 16:48:47 +08:00
这玩意儿就是访问优先级问题吧,好像带继承的语言都有。刚好这个语言里 父类属性优先级高于子类方法
iBugOne
2021-04-15 16:50:31 +08:00
Source: https://stackoverflow.com/a/51401151/5958455

简而言之,work = () => {} 是在 constructor() 里给 this.work() 的一种简写,而被明确复制的对象属性优先级总是高于在类中定义的方法,所以 Parent 里给 this.work 赋值的箭头函数“覆盖”了 Child.prototype.work
mxT52CRuqR6o5
2021-04-15 16:55:57 +08:00
父类的 work 方法是在 constructor 是挂在实例上的
子类的 work 方法是挂在 Child.prototype 上的
Kasumi20
2021-04-15 16:57:04 +08:00
class Parent {

work = function () {
console.log('This is work() on the Parent class');
}

}

和箭头函数没有关系,这种写法会定义新的字段,优先级高于原型链上的字段
waiaan
2021-04-15 17:21:08 +08:00
@Kasumi20
@iBugOne
明白了,忘了=号的作用了。谢谢。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/770886

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX