instanceof operator fails when passing an object through windows(通过窗口传递对象时,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 和源窗口的 Object 不是同一个东西,一个实例一个不会是另一个的实例.您可以使用 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 运算符失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过窗口传递对象时,instanceof 运算符失败
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
