简体   繁体   English

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

[英]Inheritance and polymorphism using arrow functions in JavaScript Classes

Why do arrow functions take precedence over function declarations in JavaScript Classes?为什么箭头函数优先于 JavaScript 类中的 function 声明?

Example:例子:


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

The parent work() method fires in this example:父 work() 方法在此示例中触发:

"This is work() on the Parent class" “这是父类上的 work()”

I just want to understand WHY the arrow function always takes precedence in JS Classes, especially in regards to Inheritance and Polymorphism.我只是想了解为什么箭头 function 在 JS 类中总是优先,尤其是在 Inheritance 和多态性方面。

It is nothing to do with being an arrow function.这与成为箭头 function 无关。 It is taking precedence because it's a class field .它具有优先权,因为它是class 字段 Class fields are added as an own property of the instance while methods are added to Child.prototype.work . Class 字段作为实例的自有属性添加,同时方法添加到Child.prototype.work Even if you change it from an arrow function to a regular function, it will still execute the class field.即使您将其从箭头 function 更改为常规 function,它仍然会执行 class 字段。

When you access kid.work , the order in which the property will be looked is当您访问kid.work时,查看属性的顺序是

  • own properties, directly under kid object (It is found here)自己的属性,直接在kid object 下(在这里可以找到)
  • Child.prototype.work
  • Parent.prototype.work
  • If still not found, it will be looked inside Object.prototype如果仍然没有找到,它将在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM