【问题标题】:How to add class method to prototype in ES7如何在 ES7 中为原型添加类方法
【发布时间】:2020-01-27 17:57:18
【问题描述】:

我对 ES7 中的一种语法感到困惑。我将一个类定义为:

class Employee2 {
  Ename = "Rahul";
  printName =  () => {
    console.log(this.Ename);
  }
}

由于类是现有原型概念的语法糖,我预计方法“printName”实际上会转到函数原型。但这并没有发生,该方法是一个对象属性。

但是,如果我这样做:

class Employee {
  Ename = "Rahul";
  printName () {
    console.log(this.Ename);
  }
}

这在 printName 进入原型的地方按预期工作。 现在我的查询:

ES7 建议使用第一个代码 Employee2 类中的语法,如果我使用它,我会错过原型上的方法定义。有没有办法实现函数原型上的方法?

【问题讨论】:

  • “ES7 建议使用第一个代码 Employee2 类中的语法” 你从哪里读到的?首先,printName 是实例的自己的 属性,就像Ename 一样。 Class field proposal

标签: javascript class arrow-functions ecmascript-2016 fat


【解决方案1】:

ES7 建议使用第一个代码 Employee2 类中的语法

没有。适当时使用。我会尽可能多地使用第二个版本。第一个版本勉强等于:

 function Employee2() {
   this.Ename = "Rahul";
   this.printName =  () => {
     console.log(this.Ename);
   };
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多