推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
waiaan

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

  •  
  •   waiaan · Apr 15, 2021 · 3365 views
    This topic created in 2038 days ago, the information mentioned may be changed or developed.
    
    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 replies  •  2021-04-15 17:21:08 +08:00
    paddistone
    paddistone
    Apr 15, 2021
    1
    这玩意儿就是访问优先级问题吧,好像带继承的语言都有。刚好这个语言里 父类属性优先级高于子类方法
    iBugOne
    iBugOne
    Apr 15, 2021
    2
    Source: https://stackoverflow.com/a/51401151/5958455

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

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

    }

    和箭头函数没有关系,这种写法会定义新的字段,优先级高于原型链上的字段
    waiaan
    waiaan
    OP
    Apr 15, 2021
    5
    @Kasumi20
    @iBugOne
    明白了,忘了=号的作用了。谢谢。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4388 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 08:43 · PVG 16:43 · LAX 00:43 · JFK 03:43
    ♥ Do have faith in what you're doing.