Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 732
vox Avatar asked Jan 18 '13 02:01

vox


People also ask

What is the use of instanceof operator?

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with Symbol.hasInstance. The object to test. Constructor to test against.

How to test if an object is not an instanceof?

To test if an object is not an instanceof a specific constructor, you can do This will always be false. ( !mycar will be evaluated before instanceof, so you always try to know if a boolean is an instance of Car ). Tip: you can click/tap on a cell for more information.

What is the use of instanceof in JavaScript?

One thing worth mentioning is instanceof evaluates to true if the object inherits from the class’s prototype: That is p instanceof Person is true since p inherits from Person.prototype. A simple example code checks the current object and returns true if the object is of the specified object type.

What is the return value of instanceof?

instanceof The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.


1 Answers

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.)

like image 149
Ry- Avatar answered Sep 30 '22 00:09

Ry-