对象的等效实例.创建和原型链

Instanceof equivalent for Object.create and prototype chains

本文关键字:原型 创建 实例 对象      更新时间:2023-09-26

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

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

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

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

我的回答很简短…

你可以使用isPrototypeOf方法,它将出现在你的对象继承自object原型的情况下,就像你的例子。

的例子:

A.isPrototypeOf(C) // true
B.isPrototypeOf(C) // true
Array.prototype.isPrototypeOf(C) // false

更多信息可以在这里阅读:Mozilla开发者网络: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
}