V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
waiaan

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

  •  
  •   waiaan · Apr 15, 2021 · 2748 views
    This topic created in 1842 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
        1
    paddistone  
       Apr 15, 2021
    这玩意儿就是访问优先级问题吧,好像带继承的语言都有。刚好这个语言里 父类属性优先级高于子类方法
    iBugOne
        2
    iBugOne  
       Apr 15, 2021
    Source: https://stackoverflow.com/a/51401151/5958455

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

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

    }

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