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

Inheritance and polymorphism using arrow functions in JavaScript Classes

为什么箭头函数优先于 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();

父 work() 方法在此示例中触发:

"This is work() on the Parent class"

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

这与箭头函数无关。它具有优先权,因为它是 class field。 Class 字段作为实例的 own 属性 添加,而方法添加到 Child.prototype.work。即使你把它从箭头函数改成常规函数,它仍然会执行class字段。

当您访问 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)