admin管理员组

文章数量:1294662

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?

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?

Share Improve this question edited Jan 4, 2012 at 21:56 mjc asked Dec 17, 2011 at 23:56 mjcmjc 3,4263 gold badges37 silver badges47 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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"

本文标签: Javascript Named Function Expressions in Internet ExplorerStack Overflow