thisArg of array.forEach does not reference as expected

若如初见. 提交于 2019-12-10 20:34:20

问题


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);

I get following output:

0 : Audi
true
undefined
1 : Volvo
true
undefined
2 : Mercedes
true
undefined

Where I don't understand why this does not reference myObj and returns undefined instead of 7. While this typeof Object returns true, I don't know which Object it references. I just know that this returns an empty Object(i.e. {})

Node.js interpreter version is v6.2.1

V8-Engine version is 5.0.71.52


回答1:


Problem

Arrow functions:

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.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));


来源:https://stackoverflow.com/questions/38127635/thisarg-of-array-foreach-does-not-reference-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!