Skip to content
Advertisement

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?

Advertisement

Answer

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.

Advertisement