ES6 循环和 forEach 中的上下文和变量作用域

Context and variable scope in ES6 loops and forEach

在 ES5 中,如果我必须在子函数中引用父函数的 this 上下文,我必须将它存储在一个变量中并使用该变量在子函数中访问它。

像这样...

//  variant 1
var self = this;
this.nums.forEach(function (v) {
if (v % 5 === 0)
   self.fives.push(v);
});

ECMAScript 有箭头函数,所以我可以避免这种情况:

// variant 2
this.nums.forEach((v) => {
 if (v % 5 === 0)
   this.fives.push(v)
})

我的问题是:如果我要在上面的 forEach 函数中声明一个变量 temp,这会污染我的全局范围吗?如果是这样会不会有性能问题和变量冲突?

for 循环中发生了类似的事情....

//variant 3
for(var i =0 ;i.......){
   var temp = "tempvariable";
   //some code here
 }

 console.log(temp);
 //output : tempvariable

variant2variant3 代码片段有什么区别?

常规函数使用执行上下文来设置this的值,这意味着在大多数情况下,this的值取决于函数的调用方式,即[的值=11=]根据函数执行的环境设置。

箭头函数没有自己的 this 值,而是使用词法作用域,这意味着箭头函数中 this 的值总是从封闭作用域继承,即它被设置到封闭执行上下文的 this 值。

这在 documentation 中也有解释

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.
....
Arrow functions capture the this value of the enclosing context

发布的第三个示例只是一个常规的 for 循环,与函数的共同点很少,无法与前两个代码示例进行比较。
for 循环在 ES2015 中的工作方式一如既往,在 for 循环中通常没有变量的特殊作用域,因为变量 (用 var 定义) 是函数范围的。

然而,ES2015 确实引入了可以是块作用域的变量,作为一个 for 循环实际上是一个块 (for (what) {block}) ,可以使用这些变量,它们是用 let 关键字或 const 关键字定义的常量 (不能更改)

对于那些喜欢代码的人

var o = {
    nums  : [1,2,3,4],
    fn    : function() {
        var self = this;
        this.nums.forEach(function(v) {
            // "this" in this context would be the window,
            // but "self" would be the object "o", hence the common use of this hack
        });

        this.nums.forEach((v) => {
            // "this" in this context, would be the object "o"
            // that happens because the "this-value" in the fn() function,
            // ... is the parent object
            // and the arrow function inherits that this-value
        });

        for (var i=0; i<this.nums.length; i++) {
            // "this" in this context is what it has always been,
            // a for-loop has the same this-value as the surrounding scope
        }
    }
}

o.fn(); // called from global context "window"