最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

class - Inheritance and polymorphism using arrow functions in JavaScript Classes - Stack Overflow

programmeradmin5浏览0评论

Why do arrow functions take precedence over function declarations in JavaScript Classes?

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 :

"This is work() on the Parent class"

I just want to understand WHY the arrow function always takes precedence in JS Classes, especially in regards to Inheritance and Polymorphism.

Why do arrow functions take precedence over function declarations in JavaScript Classes?

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 :

"This is work() on the Parent class"

I just want to understand WHY the arrow function always takes precedence in JS Classes, especially in regards to Inheritance and Polymorphism.

Share Improve this question edited Jun 10, 2020 at 10:42 Amir asked Jun 10, 2020 at 10:30 AmirAmir 2,5504 gold badges19 silver badges30 bronze badges 1
  • This is why you should not (ab)use arrow functions in instance class fields as methods. – Bergi Commented Jun 10, 2021 at 12:39
Add a ment  | 

1 Answer 1

Reset to default 10

It is nothing to do with being an arrow function. It is taking precedence because it's a class field. Class fields are added as an own property of the instance while methods are added to Child.prototype.work. Even if you change it from an arrow function to a regular function, it will still execute the class field.

When you access kid.work, the order in which the property will be looked is

  • own properties, directly under kid object (It is found here)
  • Child.prototype.work
  • Parent.prototype.work
  • If still not found, it will be looked inside 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)

发布评论

评论列表(0)

  1. 暂无评论