array.forEach的thisArg没有按预期引用

时间:2016-06-30 15:33:52

标签: javascript node.js foreach object-reference

给出以下代码:

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不引用myObj而返回undefined而不是7。 虽然this typeof Object返回true,但我不知道它引用了哪个Object。我只知道this返回一个空对象(即{}}

Node.js解释器版本是v6.2.1

V8-Engine版本为5.0.71.52

1 个答案:

答案 0 :(得分:7)

<强>问题

Arrow functions

  

箭头函数表达式function expressions相比具有更短的语法,并且词汇绑定this值(不绑定自己的this,{{3 }},argumentssuper)。箭头函数始终为new.target

解决方案1 ​​

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

解决方案2

使用闭包

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