【问题标题】:How to call parent class dynamically without mention the class name in JavaScript?如何在不提及 JavaScript 中的类名的情况下动态调用父类?
【发布时间】:2020-04-30 04:19:04
【问题描述】:

我很好奇如何调用一个类的one-level parent (not the oldest one) 来获取它的static 值并与当前类静态值相连接。例如:

class Grandpa {
  static xxx = [1,2]
}
class Father extends Grandpa {
  static xxx = [...Grandpa.xxx, 3] // how to get Grandpa's xxx value without mention Grandpa before .xxx?
}
class Child extends Father {
  static xxx = [...Father.xxx, 4] // how to get Father's xxx value without mention Father before .xxx?
}
console.log(Child.xxx) // [1,2,3,4]

怎么做?

【问题讨论】:

标签: javascript oop ecmascript-6


【解决方案1】:

据此Link:

super 关键字用于访问和调用对象的函数 父母。

您还可以在静态方法上调用 super。

class Grandpa {
  static xxx = [1,2]
}
class Father extends Grandpa {
  static xxx = [...super.xxx, 3] // how to get Grandpa's xxx value without mention Grandpa before .xxx?
}
class Child extends Father {
  static xxx = [...super.xxx, 4] // how to get Father's xxx value without mention Father before .xxx?
}
console.log(Child.xxx) // [1,2,3,4]

【讨论】:

  • 它有效。但是我也可以在non-static 方法中调用super.xxx 吗?假设我在Child 类中有一个名为getXxx() 的方法,并且我想在其中再次调用super.xxx,或者我也必须将其设为static?
  • 不。 super 也适用于非静态。阅读我添加的链接,了解有关 super 的更多信息。
  • 那么,如果一个类有两个同名的方法(static 和not),我们想用super 来调用这两个方法,这不是模棱两可吗?跨度>
  • 好的,现在我明白你之前问了什么了。你为什么要命名两个属性相同?您可以轻松查看所有这些奇怪的场景..我从来没有尝试过做一些奇怪的事情;)
猜你喜欢
  • 2010-10-28
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多