Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 507
mikeycgto Avatar asked Dec 13 '22 07:12

mikeycgto


1 Answers

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.

like image 197
Adam Rackis Avatar answered Feb 24 '23 07:02

Adam Rackis