javascript - 更改 js 函数的定义在某些浏览器中不起作用

标签 javascript function internet-explorer

我搜索了这个问题的答案,但没有找到任何东西,尽管必须有一个简单的解释。下面的函数js在不同的浏览器中显示不同的结果...有人能告诉我为什么吗?非常感谢

var i='a';

if (i=='a')  function theFunction(){alert('hi');}
else         function theFunction(){alert('bye');};

theFunction();

//ff results in hi
//ie results in bye
//chrome results in bye

最佳答案

问题在于您在 if block 内使用了函数声明。

来自ECMA-262 :

NOTE Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable differences, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context.

如果您尝试在严格模式下使用代码,您会得到

SyntaxError: in strict mode code, functions may be declared only at top level or immediately within another function

相反,您可以使用

var i='a',
    theFunction;

if (i=='a')  theFunction = function(){alert('hi');}
else         theFunction = function(){alert('bye');};
theFunction();

或者,如果您的代码足够简单(如上面的示例),请使用三元运算符:

var theFunction = i=='a'
    ? function(){alert('hi');}
    : function(){alert('bye');};

关于javascript - 更改 js 函数的定义在某些浏览器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20314279/

相关文章:

javascript - 使用日期范围过滤 Angular ui Bootstrap

c++ - 有没有办法让函数成为参数?

JavaScript 函数构造函数解析安全性

c++ - 函数指针和 C++ 模板

javascript - 从具有特定 src 属性的数组中抓取图像

javascript - 浏览器无法解析 AngularJS 代码

javascript - 页面加载时未触发复选框更改

javascript - AngularJs 模板未在 Internet Explorer 8 中加载

javascript - Internet Explorer 8 错误,需要对象 (JavaScript)

JQuery Cycle 插件、SIFR 和 PNG 修复 - IE 中的奇怪行为