Why does the following code not work in Internet Explorer (I\'ve only tested in IE8 so far):
(function(){
this.foo = function foo(){};
foo.prototype = {
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 read on this topic, check out this link
The short of it is that the inner, named function expression is treated as a function declaration, and hoisted up to places it should never, ever be.
In IE, the usage of foo.prototype is "ambigious" because NFE identifiers are leaked to the containing scope.
Since the local leaked foo is closer than the global foo, foo.prototype will
augment the local foo, not window.foo.
After you leave the outer function, the local foo is lost and the global foo doesn't have .prototype.bar
for the above reasons.
You can resolve the ambiguity by:
(function(){
this.foo = function foo(){};
this.foo.prototype = {
bar:function(){
return 'bar';
}
};
})();
var x = new foo;
console.log(x.bar()) //"bar"