在JavaScript类中使用箭头函数的继承和多态性。

问题描述 投票:2回答:1

为什么在JavaScript类中,箭头函数优先于函数声明?

例子 :


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

在这个例子中,parent work()方法会发生火灾。

"这是父类上的work()"

我只是想了解 为什么 在JS类中,箭头函数总是优先于函数声明,尤其是在继承和多态方面。

javascript class inheritance polymorphism es6-class
1个回答
4
投票

这与作为一个箭头函数无关。它是优先的,因为它是一个 班级领域. 类字段被添加为 自己 属性,而方法被添加到 Child.prototype.work. 即使你把它从箭头函数改为普通函数,它仍然会执行类字段。

当你访问 kid.work财产的查看顺序是

  • 自有财产,直属 kid 对象
  • Child.prototype.work
  • Parent.prototype.work
  • 如果还是没有找到,就会在里面找。Object.prototype

class Parent {
  // doesn't matter if it an arrow function or not
  // prop = <something> is a class field
  work = function() {
    console.log('This is work() on the Parent class');
  }
}

class Child extends Parent {
  // this goes on Child.prototype not on the instance of Child
  work() {
    console.log("This is work() on the Child class ");
  }
}

const kid = new Child();

// true 
console.log( kid.hasOwnProperty("work") )

// true
console.log( Child.prototype.hasOwnProperty("work") )

// false 
// because work inside Parent is added to each instance
console.log( Parent.prototype.hasOwnProperty("work") )

kid.work();

// How to force the Child method
Child.prototype.work.call(kid)
© www.soinside.com 2019 - 2024. All rights reserved.