Given following code:
const theArray = ['Audi','Volvo','Mercedes'];
const myObj = {a: 7};
theArray.forEach((value, index, array) => {
console.log(index + ' : ' + value);
console.log(array === theArray);
console.log(this.a);
}, myObj);
0 : Audi
true
undefined
1 : Volvo
true
undefined
2 : Mercedes
true
undefined
this
this typeof Object
this
Problem
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the
this
value (does not bind its ownthis
,arguments
,super
, ornew.target
). Arrow functions are always anonymous.
Solution 1
Use function
const theArray = ['Audi','Volvo','Mercedes'];
const myObj = {a: 7};
theArray.forEach(function (value, index, array) {
console.log(index + ' : ' + value);
console.log(array === theArray);
console.log(this.a);
}, myObj);
Solution 2
Use a closure
var abc = 'abc';
const theArray = ['Audi','Volvo','Mercedes'];
const myObj = {a: 7};
theArray.forEach((obj => (value, index, array) => {
console.log(index + ' : ' + value);
console.log(array === theArray);
console.log(obj.a);
console.log(this.abc);
})(myObj));