mjc
mjc

Reputation: 3426

Javascript Named Function Expressions in Internet Explorer

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 = {
    bar:function(){
      return 'bar';
    }
  };
})();

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

If I change foo's assignment to the following, the code works just fine:

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

I imagine it's something to do with named functions in IE's Javascript engine. The code works fine in Chrome and Firefox.

Any ideas?

Upvotes: 4

Views: 2327

Answers (2)

Adam Rackis
Adam Rackis

Reputation: 83358

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.

Upvotes: 8

Esailija
Esailija

Reputation: 140220

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"

Upvotes: 5

Related Questions