当通过窗口传递对象时,instanceof运算符失败 [英] instanceof operator fails when passing an object through windows

查看:99
本文介绍了当通过窗口传递对象时,instanceof运算符失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在窗口之间传递数据,我通过 window.open 方法打开新窗口,并将新打开的窗口的属性设置为对象。这使我不仅可以传递数据,还可以共享变量的实例,这意味着如果我在一个窗口上修改对象或其任何派生属性,它会在所有窗口上修改它。

In order to pass data between windows, I open new windows via the window.open method and set a property of the newly opened window to an object. This allows me not only to pass data, but to share the instance of the variable, meaning if I modify the object, or any of its derived properties, on one window, it modifies it on all windows.

然而,问题是使用instanceof运算符非常有趣。

The problem, however, is something is going very funny with the instanceof operator.

当我这样做时

typeof m
m instanceof Object

第一行返回object,而第二行返回 false

The first line returns "object" while the second one returns false.

我特别需要instanceof运算符来检查数组和对象。

I specifically need the instanceof operator to check between arrays and objects.

这是一个例子的小提示(警告:尝试打开一个页面加载窗口,因此弹出窗口阻止程序可能阻止它)。 http://jsfiddle.net/Chakra/mxf2P/1/

Here is a fiddle of an example (WARNING: tries to open a window on page load, so a popup blocker might block it). http://jsfiddle.net/Chakra/mxf2P/1/

推荐答案

因为你的窗口的对象和源窗口的对象不是一回事,一个实例不会是另一个实例。您可以使用 Object.prototype.toString 来区分对象和数组:

Since your window's Object and the source window's Object aren't the same thing, an instance of one won't be an instance of the other. You can use Object.prototype.toString to distinguish between objects and arrays:

if(Object.prototype.toString.call(m) === '[object Array]') {
    // It's an array
} else {
    // It's not
}

您还可以使用 Array.isArray ,如果有的话。

You can also use Array.isArray, if available.

这是一个演示。(顺便说一下,它使用< iframe> 而不是弹出窗口。)

Here's a demo. (It uses an <iframe> instead of a popup, by the way.)

这篇关于当通过窗口传递对象时,instanceof运算符失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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