考虑这样一个带有原型链的对象:
var A = {};
var B = Object.create(A);
var C = Object.create(B);
如果 C 在其原型链中有 A,如何检查运行时?
instanceof
不适合,因为它旨在与构造函数一起使用,我在这里没有使用。
考虑这样一个带有原型链的对象:
var A = {};
var B = Object.create(A);
var C = Object.create(B);
如果 C 在其原型链中有 A,如何检查运行时?
instanceof
不适合,因为它旨在与构造函数一起使用,我在这里没有使用。
My answer will be short…</p>
You could use the isPrototypeOf
method, which will be present in case your object inherits from the Object prototype, like your example.
example:
A.isPrototypeOf(C) // true
B.isPrototypeOf(C) // true
Array.prototype.isPrototypeOf(C) // false
More info can be read here: Mozilla Developer Network: isPrototypeOf
Object.getPrototypeOf
您可以通过递归调用来遍历原型链:http: //jsfiddle.net/Xdze8/。
function isInPrototypeChain(topMost, itemToSearchFor) {
var p = topMost;
do {
if(p === itemToSearchFor) {
return true;
}
p = Object.getPrototypeOf(p); // prototype of current
} while(p); // while not null (after last chain)
return false; // only get here if the `if` clause was never passed, so not found in chain
}