gpt4 book ai didi

Javascript - 如何更改类的父类?

转载 作者:行者123 更新时间:2023-12-05 07:31:23 30 4
gpt4 key购买 nike

假设我们有 3 个类

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

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

因此 new B() instanceof C 将为 true
new B() instanceof A 将为 false

最佳答案

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

关于Javascript - 如何更改类的父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51823432/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com