【问题标题】:Javascript - How to change the parent class of a class?Javascript - 如何更改类的父类?
【发布时间】:2018-08-13 13:24:05
【问题描述】:

假设我们有 3 个类

class A {}
class B extends A {}
class C {}

是否有可能使 B 扩展 C 而不是 A

所以new B() instanceof C 将是true
new B() instanceof A 将是false

【问题讨论】:

  • 动态?没有
  • 残酷的世界:,(
  • 为什么要将它命名为B?如果和B不一样?
  • 这个解决方案对您有用吗? stackoverflow.com/a/51411186/1438757
  • @appleapple 我想保留 B 类的所有方法和属性。如果我这样做new B() instanceof C,那应该是真的。 B变成了C,不再是A了。我没有来自 A 的任何方法或属性。

标签: javascript class inheritance


【解决方案1】:
B.prototype.__proto__ = C.prototype

这似乎是正确的答案。
但还是it shouldn't be used

这是演示

class A {
  f(){
    console.log("I am a A")
  }
}

class B extends A {}

class C {
  f(){
    console.log("I am a C")
  }
}

// ----- test B -----
new B().f() // "I am a A";
console.log("B is an A: " + (new B instanceof A));
console.log("B is an C: " + (new B instanceof C));



// ------- CHANGE ------
console.log("Changing B's parent class to C !");
B.prototype.__proto__ = C.prototype;


// ------- retest -------
new B().f() // "I am a C";
console.log("B is an A: " + (new B instanceof A));
console.log("B is an C: " + (new B instanceof C));

【讨论】:

猜你喜欢
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
相关资源
最近更新 更多