if/else 语句中的函数声明? [英] Function declarations inside if/else statements?

查看:41
本文介绍了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); //writes "foo" even though 'foo' !== 'bar'

此示例在 Chrome 和 Firefox 中产生不同的输出.Chrome 输出 foo 而 FF 输出 19.

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

推荐答案

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

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.

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

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 语句中的函数声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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