Sem*_*lon 17 javascript prototypal-inheritance ecmascript-6
我有一种情况需要检查构造函数(X)在其原型链中是否有另一个构造函数(Y)(或者是Y本身).
最快的方法可能是这样做(new X()) instanceof Y.在这种情况下,这不是一个选项,因为有问题的构造函数可能会在没有有效参数的情况下实例化.
我考虑的下一个方法是:
const doesInherit = (A, B) => {
while (A) {
if (A === B) return true;
A = Object.getPrototypeOf(A);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
这是行得通的,但我无法摆脱这种感觉,即我错过了一些更简单的检查方法.有吗?
Fel*_*ing 27
由于方式instanceof有效,你应该能够做到
A.prototype instanceof B
Run Code Online (Sandbox Code Playgroud)
但这只会测试继承,你应该比较A === B测试自我引用:
A === B || A.prototype instanceof B
Run Code Online (Sandbox Code Playgroud)
class A {}
class B extends A {}
class C extends B {}
console.log(C === C) // true
console.log(C.prototype instanceof B) // true
console.log(C.prototype instanceof A) // true
Run Code Online (Sandbox Code Playgroud)
instanceof 基本上实现如下:
function instanceof(obj, Constr) {
var proto;
while ((proto = Object.getProtoypeOf(obj)) {
if (proto === Constr.prototype) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
它遍历对象的原型链,并检查是否有任何原型等于构造函数prototype属性.
所以几乎就像你在做什么,但在内部.
Oka*_*Oka 13
还有Object.prototype.isPrototypeOf().看起来像一个完美的用例,不是吗?
class A {}
class B extends A {}
class C extends B {}
console.log(C === C)
console.log(B.isPrototypeOf(C))
console.log(A.isPrototypeOf(C))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7489 次 |
| 最近记录: |