我搜索了这个问题的答案,但没有找到任何东西,尽管必须有一个简单的解释。下面的函数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/