Javascript在Internet Explorer中命名为函数表达式 [英] Javascript Named Function Expressions in Internet Explorer

查看:108
本文介绍了Javascript在Internet Explorer中命名为函数表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码在Internet Explorer中不起作用(我目前仅在IE8中测试过):

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

如果我将 foo 的分配更改为以下内容,则代码可以正常运行:

If I change foo's assignment to the following, the code works just fine:

var foo = this.foo = function(){};

我想这与IE的Javascript引擎中的命名函数有关。该代码在Chrome和Firefox中运行良好。

I imagine it's something to do with named functions in IE's Javascript engine. The code works fine in Chrome and Firefox.

任何想法?

推荐答案

IE有很多问题命名函数表达式。正如你在问题中所说,坚持这一点:

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.

这篇关于Javascript在Internet Explorer中命名为函数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆