简体   繁体   English

如何在ECMAScript 5中具有块作用域

[英]How to have block scopes in ECMAScript 5

When I was reading about ES 6 features, I found let which is used to create block scopes. 当我阅读有关ES 6的功能时,我发现let用于创建块作用域。 This link has nice explanation on ES6 features and let statement. 链接对ES6功能和let语句有很好的解释。 So how do developers create this block scopes in older versions of ECMAScript, like ES5. 因此,开发人员如何在早期版本的ECMAScript(如ES5)中创建此block scopes

The following code snippet explains let 以下代码段说明了let

var es = [];
for (var i = 0; i < 10; i++) {
  let c = i;
  es[i] = function () {
    console.log("Upcoming edition of ECMAScript is ES" + c);
  };
}
es[6](); // Upcoming edition of ECMAScript is ES6

What is the equivalent code in ES5? ES5中的等效代码是什么?

Above code snippet without let , outputs 10 for i since it is in global scope. 上面没有let代码段,因为它在全局范围内,所以为i输出10

var es = [];
for (var i = 0; i < 10; i++) {
  es[i] = function () {
    console.log("Upcoming edition of ECMAScript is ES" + i);
  };
}
es[6](); // Upcoming edition of ECMAScript is ES10

This link has ES6 equivalents in ES5 and it recommends to use IIFE for block scopes. 链接在ES5中具有等效于ES6的链接 ,建议对块作用域使用IIFE But I am not sure, how to use IIFE in the current scenario. 但是我不确定在当前情况下如何使用IIFE。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Thanks in advance. 提前致谢。

it recommends to use IIFE for block scopes. 建议将IIFE用于块范围。

In ES5, only calling a function creates a new scope. 在ES5中,仅调用函数会创建新作用域。 So "obviously", if you want to create a new scope (per iteration), you have to call a function. 因此,“显然”,如果要创建新作用域(每次迭代),则必须调用一个函数。 That's what an IIFE does: It creates a new function and calls it immediately. IIFE就是这样做的:它创建一个新函数并立即调用它。

Any variable that would be block scoped (eg via let ) would become a parameter of the function and initial values would be passed as arguments. 任何将在块范围内(例如,通过let )的变量都将成为函数的参数,并且初始值将作为参数传递。

Example: 例:

for (var i = 0; i < 10; i++) {
  (function(c) {
    es[i] = function () {
      console.log("Upcoming edition of ECMAScript is ES" + c);
    };
  }(i));
}

This is simplified of course and there may be cases that would require more elaborate solutions. 当然这是简化的,并且在某些情况下可能需要更详尽的解决方案。

The current best practice is to write ES2015 (ES6) and run your code through a preprocessor like Babel . 当前的最佳实践是编写ES2015(ES6)并通过像Babel这样的预处理器运行代码。 Babel takes of the implementation details of supporting let on older browsers. Babel详细介绍了在较旧的浏览器上支持let的实现细节。

If you want to use ES5 directly, you can create an anonymous function that is passed the value of i in each iteration. 如果要直接使用ES5,则可以创建一个匿名函数 ,该函数在每次迭代中均传递i的值。

var es = [];
for (var i = 0; i < 10; i++) {
  (function (i) {
    es[i] = function () {
      console.log("Upcoming edition of ECMAScript is ES" + i);
    };
  })(i);
}
es[6]();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM