本文介绍了if / else语句中的函数声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数声明是如何处理的?

  var abc =''; 
if(1 === 0){
function a(){
abc = 7;

} else if('a'==='a'){
function a(){
abc = 19;
}
} else if('foo'==='bar'){
function a(){
abc ='foo';
}
}
a();
document.write(abc); //写出foo即使'foo'!=='bar'

Chrome和Firefox中的输出。 Chrome的输出 foo ,而FF输出 19 。

解决方案

当提出这个问题时,ECMAScript 5(ES5)很流行。在严格的ES5模式下,如果问题中显示块,函数声明不能​​嵌套在中。在非严格模式下,结果是不可预测的。不同的浏览器和引擎在块内处理函数声明时实现了自己的规则。

截至2018年,许多浏览器都支持ECMAScript 2015(ES2015)函数声明现在允许在块内部。在ES2015环境中,块内的函数声明将在该块内进行限定。问题中的代码将导致未定义的函数错误,因为如果函数 a 仅在范围内声明,语句,因此不存在于全局范围中。



如果您需要有条件地定义一个函数,那么您应该使用。


How are function declarations handled?

var abc = '';
if(1 === 0){
    function a(){
        abc = 7;
    }
}else if('a' === 'a'){
    function a(){
        abc = 19;
    }
}else if('foo' === 'bar'){
    function a(){
        abc = 'foo';
    }
}
a();
document.write(abc); //writes "foo" even though 'foo' !== 'bar'

This example produces different outputs in Chrome and Firefox. Chrome outputs foo while FF outputs 19.

解决方案

When this question was asked, ECMAScript 5 (ES5) was prevalent. In strict mode of ES5, function declarations cannot be nested inside of an if block as shown in the question. In non-strict mode, the results were unpredictable. Different browsers and engines implemented their own rules for how they would handle function declarations inside blocks.

As of 2018, many browsers support ECMAScript 2015 (ES2015) to the extent that function declarations are now allowed inside blocks. In an ES2015 environment, a function declaration inside of a block will be scoped inside that block. The code in the question will result in an undefined function error because the function a is only declared within the scope of if statements and therefore doesn't exist in the global scope.

If you need to conditionally define a function, then you should use function expressions.

这篇关于if / else语句中的函数声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 02:26
查看更多