25

Consider such an object with a prototype chain:

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

How to check in runtime if C has A in its prototype chain?

instanceof doesn't fit as it's designed to work with constructor functions, which I'm not using here.

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

You could iterate back through the prototype chain by calling Object.getPrototypeOf recursively: 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 に答える