Context and scope of variables in ES6 and forEach loops

In ES5, if I need to refer to the context of a thisparent function in a child function, I have to store it in a variable and access it inside the child function using this variable.

Something like that...

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

ECMAScript has arrow functions, so I can avoid this:

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

The question I have is: If I declare a variable tempinside my function forEachabove, would it pollute my global scope? Should this have performance problems and variable conflicts?

Something similar happens in a loop ...

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

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

What is the difference between options2 and options 3 code snippets?

+4
1

this, , this , , this , .

this, , this , this .

,

, this( , undefined , , " " ..). - .
....
Arrow

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"
+5

All Articles