Javascript Named Function Expressions in Internet Explorer

Why the following code does not work in Internet Explorer (I tested only in IE8 so far):

(function(){ this.foo = function foo(){}; foo.prototype = { bar:function(){ return 'bar'; } }; })(); var x = new foo; console.log(x.bar()) // Error: Object doesn't support this property or method 

If I change the purpose of foo as follows, the code works very well:

 var foo = this.foo = function(){}; 

I assume this is due to named functions in IE Javascript. The code works fine in Chrome and Firefox.

Any ideas?

+4
javascript internet-explorer
source share
2 answers

IE has a lot of problems with named function expressions. As you said in your question, stick with this:

 this.foo = function (){}; 

For an in-depth, grueling reading on this subject, this link

In short, an internal named expression of a function is considered as a declare function and rises to the places where it should never be.

+8
source share

In IE, the use of foo.prototype is "ambiguous", as NFE identifiers leak into the content area. Since the local foo leak is closer than the global foo, foo.prototype will add the local foo , not window.foo .

After you leave the external function, the local foo will be lost, and the global foo will not .prototype.bar for the above reasons.

You can eliminate the ambiguity with:

 (function(){ this.foo = function foo(){}; this.foo.prototype = { bar:function(){ return 'bar'; } }; })(); var x = new foo; console.log(x.bar()) //"bar" 
+5
source share

All Articles