25

考虑这样一个带有原型链的对象:

var A = {};
var B = Object.create(A);
var C = Object.create(B);

如果 C 在其原型链中有 A,如何检查运行时?

instanceof不适合,因为它旨在与构造函数一起使用,我在这里没有使用。

4

2 回答 2

22

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

于 2012-02-06T00:21:29.000 回答
4

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
}
于 2011-12-09T17:31:29.950 回答