【发布时间】:2013-01-07 07:26:09
【问题描述】:
例如:
function A(){}
function B(){}
B.prototype = new A();
如何检查B类是否继承A类?
【问题讨论】:
标签: javascript class inheritance
例如:
function A(){}
function B(){}
B.prototype = new A();
如何检查B类是否继承A类?
【问题讨论】:
标签: javascript class inheritance
尝试以下方法:
ChildClass.prototype instanceof ParentClass
【讨论】:
class 怎么样? class A extends B{} 那么我该如何检查类A的继承情况@
A.prototype ... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
你可以测试直接继承
B.prototype.constructor === A
要测试间接继承,您可以使用:
B.prototype instanceof A
(这第二个解决方案首先由 Nirvana Tikku 给出)
【讨论】:
回到 2017 年:
检查这是否适合你
ParentClass.isPrototypeOf(ChildClass)
如果您想要防止阴影的替代方案:
const isPrototypeOf = Function.call.bind(Object.prototype.isPrototypeOf);
// Usage:
isPrototypeOf(ParentClass, ChildClass); // true or false
【讨论】:
陷阱:请注意,如果您使用多个执行上下文/窗口,instanceof 将无法按预期工作。见§§。
另外,根据https://johnresig.com/blog/objectgetprototypeof/,这是与instanceof 相同的替代实现:
function f(_, C) { // instanceof Polyfill
while (_ != null) {
if (_ == C.prototype)
return true;
_ = _.__proto__;
}
return false;
}
修改它以直接检查类给我们:
function f(ChildClass, ParentClass) {
_ = ChildClass.prototype;
while (_ != null) {
if (_ == C.prototype)
return true;
_ = _.__proto__;
}
return false;
}
instanceof 本身会检查 obj.proto 是否为 f.prototype,因此:
function A(){};
A.prototype = Array.prototype;
[]instanceof Array // true
和:
function A(){}
_ = new A();
// then change prototype:
A.prototype = [];
/*false:*/ _ instanceof A
// then change back:
A.prototype = _.__proto__
_ instanceof A //true
和:
function A(){}; function B(){};
B.prototype=Object.prototype;
/*true:*/ new A()instanceof B
如果不相等,则在检查中将 proto 与 proto 的 proto 交换,然后将 proto 的 proto 的 proto 交换,以此类推。因此:
function A(){}; _ = new A()
_.__proto__.__proto__ = Array.prototype
g instanceof Array //true
和:
function A(){}
A.prototype.__proto__ = Array.prototype
g instanceof Array //true
和:
f=()=>{};
f.prototype=Element.prototype
document.documentElement instanceof f //true
document.documentElement.__proto__.__proto__=[];
document.documentElement instanceof f //false
【讨论】:
我认为 Simon 在他的问题中不是指 B.prototype = new A(),因为这肯定不是在 JavaScript 中链接原型的方式。
假设 B 扩展 A,使用 Object.prototype.isPrototypeOf.call(A.prototype, B.prototype)
【讨论】:
class 之前,B.prototype = new A() 确实是链接原型的有效方式(对于那些想要经典风格继承的人)。