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

Ami*_*mir 4 javascript polymorphism inheritance class es6-class

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

在这个例子中,父 work() 方法被触发:

“这是父类上的 work()”

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

adi*_*iga 8

这与成为箭头函数无关。它优先,因为它是一个类字段。类字段被添加为实例自己的属性,而方法被添加到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)
Run Code Online (Sandbox Code Playgroud)