V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
waiaan
V2EX  ›  JavaScript

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

  •  
  •   waiaan · 2021-04-15 16:41:41 +08:00 · 1879 次点击
    这是一个创建于 1104 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    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();
    

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

    5 条回复    2021-04-15 17:21:08 +08:00
    paddistone
        1
    paddistone  
       2021-04-15 16:48:47 +08:00
    这玩意儿就是访问优先级问题吧,好像带继承的语言都有。刚好这个语言里 父类属性优先级高于子类方法
    iBugOne
        2
    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
        3
    mxT52CRuqR6o5  
       2021-04-15 16:55:57 +08:00   ❤️ 1
    父类的 work 方法是在 constructor 是挂在实例上的
    子类的 work 方法是挂在 Child.prototype 上的
    Kasumi20
        4
    Kasumi20  
       2021-04-15 16:57:04 +08:00   ❤️ 1
    class Parent {

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

    }

    和箭头函数没有关系,这种写法会定义新的字段,优先级高于原型链上的字段
    waiaan
        5
    waiaan  
    OP
       2021-04-15 17:21:08 +08:00
    @Kasumi20
    @iBugOne
    明白了,忘了=号的作用了。谢谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3290 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 111ms · UTC 13:24 · PVG 21:24 · LAX 06:24 · JFK 09:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.