Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does typeof val === 'object' && val.constructor === Array fail if val created in other frame? [duplicate]

Tags:

javascript

So the following code alerts false twice:

window.onload = function(){
                    alert(window.myframe.myarray instanceof Array);
                    alert(window.myframe.myarray.constructor === Array);
                }

When there's an iframe in the page named "myframe" that has contains an array called "myarray". If the array is moved into the main page (as opposed to the iframe), then the code alerts true twice as expected. Does anyone know why this is?

like image 234
zjmiller Avatar asked Jun 24 '11 20:06

zjmiller


People also ask

Why does typeof null return object?

The reasoning behind this is that null , in contrast with undefined , was (and still is) often used where objects appear. In other words, null is often used to signify an empty reference to an object. When Brendan Eich created JavaScript, he followed the same paradigm, and it made sense (arguably) to return "object" .

Why in JS typeof array is object?

This because in javascript all derived data type is always a type object. Included functions and array. In case you need to check if it's an array you can use isArray method of Array. and the result will be the same as the previous one.

What is the use of typeof () function?

The typeof operator returns a string indicating the type of the operand's value.

What is the result of typeof typeof function?

There are six possible values that typeof returns: object, boolean, function, number, string, and undefined. The following table summarizes possible values returned by the typeof operator.


2 Answers

function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]';
}

Long explanation here about why .constructor fails with frames.

The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]’s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail:

like image 130
epascarello Avatar answered Oct 20 '22 00:10

epascarello


The two windows each create their own global script environment.

The Array constructor of one is not the same object as the other.

var win2=window.myframe;
alert(win2.myarray instanceof win2.Array); returns true
like image 36
kennebec Avatar answered Oct 20 '22 00:10

kennebec