是否可以确定使用Object.create创建的对象是否继承自JavaScript中的Array? [英] Is it possible to determine if an object created with Object.create inherits from Array in JavaScript?

查看:81
本文介绍了是否可以确定使用Object.create创建的对象是否继承自JavaScript中的Array?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Identifying which objects are which is complicated in JavaScript, and figuring out which objects are arrays has something of a hacky solution. Fortunately, it manages to work in both of the following cases:

Object.prototype.toString.call([]);           // [object Array]
Object.prototype.toString.call(new Array());  // [object Array]

很好,没有 [object Object] 即将到来!遗憾的是,这种方法仍然设法失败:

Great, no [object Object] in sight! Sadly, this method still manages to fail with this:

var arr = Object.create(Array.prototype);
Object.prototype.toString.call(arr);          // [object Object]

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

This is frustrating, so say the least. My arr object has all the methods of an array, it functions like an array, and for all purposes, it is an array. Yet JavaScript doesn't provide the tools to identify it as such.

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

Is there any way to figure out if an object inherits from a particular prototype? I suppose you could iterate through the prototypes like so:

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

但感觉有点黑客。有没有更干净的方法?

But it feels a tad hacky. Is there any cleaner approach?

推荐答案

instanceof 运算符?对于所有情况,它返回 true

How about an instanceof operator? It returns true for all your cases:

[] instanceof Array //true
new Array() instanceof Array //true
Object.create(Array.prototype) instanceof Array //true

但是:

Object.create(Array.prototype) instanceof Object //also true

所以要小心。

这篇关于是否可以确定使用Object.create创建的对象是否继承自JavaScript中的Array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆