Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript - instanceof operator fails when passing an object through windows

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.

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

When I do

typeof m
m instanceof Object

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

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

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

You can also use Array.isArray, if available.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...