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 badges2 Answers
Reset to default 8IE 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
版权声明:本文标题:Javascript Named Function Expressions in Internet Explorer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741606648a2388016.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论