Javascript Named Function Expressions in Internet Explorer

后端 未结 2 969
不思量自难忘°
不思量自难忘° 2020-12-09 23:33

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 = {         


        
相关标签:
2条回答
  • 2020-12-09 23:58

    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.

    0 讨论(0)
  • 2020-12-10 00:13

    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"
    
    0 讨论(0)
提交回复
热议问题