sainture
4/3/2016 - 6:58 AM

ECMA 6 Arrow Functions

ECMA 6 Arrow Functions

// old way
items.forEach(function(x) {
console.log(x);
incrementedItems.push(x+1);
});

// new way
items.forEach((x) => {
console.log(x);
incrementedItems.push(x+1);
});

incrementedItems = items.map((x) => x+1);

/* There is one important difference, however: arrow functions do not set a local copy of this ,
arguments , super , or new.target . When this is used inside an arrow function
JavaScript uses the this from the outer scope. Consider the following example: 
*/

class Toppings {
constructor(toppings) {
this.toppings = Array.isArray(toppings) ? toppings : [];
}
outputList() {
this.toppings.forEach(function(topping, i) {
console.log(topping, i + '/' + this.toppings.length); // no this
})
}
}
var ctrl = new Toppings(['cheese', 'lettuce']);
ctrl.outputList();

// above code will not work because 'this' is undefined inside the anonymous function (forEach)
// Now, let's change the method to use the arrow function:

class Toppings {
constructor(toppings) {
this.toppings = Array.isArray(toppings) ? toppings : [];
}
outputList() {
this.toppings
.forEach((topping, i) => console.log(topping, i + '/' + this.toppings.length); // `this` works!
)}
}
var ctrl = new Toppings(['cheese', 'lettuce']);

// Here this inside the arrow function refers to the instance variable.