是否可以确定使用Object.create创建的对象是否继承自JavaScript中的Array?

Ale*_*ing 7 javascript prototypal-inheritance ecmascript-5

确定哪些对象在JavaScript 中是复杂的,并确定哪些对象是数组有一些hacky解决方案.幸运的是,它设法在以下两种情况下工作:

Object.prototype.toString.call([]);           // [object Array]
Object.prototype.toString.call(new Array());  // [object Array]
Run Code Online (Sandbox Code Playgroud)

很棒,没有[object Object]在视线中!可悲的是,这种方法仍然设法失败:

var arr = Object.create(Array.prototype);
Object.prototype.toString.call(arr);          // [object Object]
Run Code Online (Sandbox Code Playgroud)

这是令人沮丧的,所以至少可以这么说.我的arr对象具有数组的所有方法,它的功能类似于数组,并且出于所有目的,它一个数组.然而,JavaScript并没有提供识别它的工具.

有没有办法弄清楚一个对象是否继承了特定的原型?我想你可以像这样迭代原型:

function inherits(obj, proto) {
    while (obj != null) {
        if (obj == proto) return true;
        obj = Object.getPrototypeOf(obj);
    }
    return false;
}

inherits(Object.create(Array.prototype), Array.prototype);  // true
Run Code Online (Sandbox Code Playgroud)

但感觉有点黑客.有没有更清洁的方法?

Art*_*oev 2

一个instanceof操作符怎么样?它会返回true您的所有案例:

[] instanceof Array //true
new Array() instanceof Array //true
Object.create(Array.prototype) instanceof Array //true
Run Code Online (Sandbox Code Playgroud)

然而:

Object.create(Array.prototype) instanceof Object //also true
Run Code Online (Sandbox Code Playgroud)

所以要小心。