【问题标题】:JavaScript Class Constructor - Is Constructor Called as Parent?JavaScript 类构造函数 - 构造函数被称为父级吗?
【发布时间】:2018-10-02 19:00:53
【问题描述】:

如果我创建以下类,Class1 中是否有任何方法可以检测实例何时实际上是 Class2 之一,而不知道 Class2 的任何信息?

即Class1 可以判断它是什么时候扩展的父类吗?

class Class1 {
  constructor() {
    // Code to detect whether parent here
  }
}

class Class2 extends Class1 {
  constructor() {
    super();
  }
}

【问题讨论】:

  • 你为什么想知道?
  • if (this.constructor !== Class1) { /* instance is some other inherited type */ }

标签: javascript class ecmascript-6 metaprogramming


【解决方案1】:

这就是 new.target 的用途 - 它为您提供了调用 new 的构造函数。所以

class Class1 {
  constructor() {
    if (new.target != Class1) {
      // Class1 is used as a parent class
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多