Javascript-如何更改类的父类?

时间:2018-08-13 13:24:06

标签: javascript class inheritance

假设我们有3个班级

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

是否可以使B扩展C而不是A

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

1 个答案:

答案 0 :(得分:0)

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));