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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With