草庐IT

javascript - Douglas Crockford 所说的 'constructed in a different window or frame' 是什么意思?

coder 2025-03-16 原文

Douglas Crockford 在编写 is_array() 测试时说它将无法识别在不同窗口或框架中构造的数组,这是什么意思?

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        value.constructor === Array;

为什么以下内容跨窗口和框架工作?

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

最佳答案

例如,如果您有一个 iframe,它有自己的 window,其中构造的任何 Array 都会使另一个 失败窗口的测试。这是因为最后一个条件假设当前 windowArray 是一个不同的对象。

var isArray = document.querySelector("iframe").contentWindow.Array === Array; 
// false (wrong, it *is* an array)

jsFiddle .

后者通过知道 typeof 总是说 Array 是一个 “object” 来工作,以及寻找存在于数组

但是,它可以愚弄,方法是构造一个看起来像数组的对象。

var isArray = is_array(Object.create({length: 0, splice: function() {}}));
// true (wrong, it *isn't* an array)

jsFiddle .

另一种方法是调用ObjecttoString()方法,返回内部类。

var isArray = ({}).toString.call(value) == "[object Array]";
// true (correct, it's an array)

jsFiddle .

这在多窗口环境中工作并且不能被欺骗(虽然以这种方式检查它有更多的开销,但永远不可能成为瓶颈) .

关于javascript - Douglas Crockford 所说的 'constructed in a different window or frame' 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164415/

有关javascript - Douglas Crockford 所说的 'constructed in a different window or frame' 是什么意思?的更多相关文章

随机推荐