IE8 Why does typeof behave differently in child windows?

I had a problem understanding typeof mechanics in IE8.

I have the following JavaScript code in "parent.html":

var myNewWindow = window.open('child.html'); myNewWindow.sayhi = function() { alert('Hi!'); } 

In parent.html we open the JavaScript console (F12). We are testing the type and looking right.

 typeof myNewWindow.sayhi "function" 

But if I open the console and do some tests in the child window, the results will be somehow strange.

 typeof this.sayhi "object" 

The fact is that you can call the "object". this.sayhi () shows a warning.

Even underscoreJS gets confused

 _.isFunction(this.sayhi) false 

Can someone explain why the function present in the window (this), but declared in the external window, is not recognized as a function, but as an IE8 object?

By the way, some say that I should look at the answer in: typeof window.close is different for IE .

Guess what? He still says this thing is an object:

 Object.prototype.toString.call(this.sayhi) '[object Object]' 
+4
source share
1 answer

This is apparently due to the fact that typeof internally checks whether the element under test inherits from the current Function object. Since the function was created in another window and inherited from another Function object, the check is not performed.

To prove this, in the console of the child window, type:

this.sayhi instanceof Function > you should get false

this.sayhi instanceof window.opener.Function > you should get true

Related article

On a side note, you should see the same problem with all native types ( Function , Array , etc.)

+2
source

All Articles