array.forEach 的 thisArg 未按预期引用
thisArg of array.forEach does not reference as expected
给定以下代码:
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 和 returns undefined 而不是 7。
虽然 this typeof Object
returns 是真的,但我不知道它引用了哪个对象。我只知道 this
returns 一个空对象(即 {})
Node.js解释器版本为v6.2.1
V8-引擎版本为5.0.71.52
问题
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.
解决方案 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));
给定以下代码:
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 和 returns undefined 而不是 7。
虽然 this typeof Object
returns 是真的,但我不知道它引用了哪个对象。我只知道 this
returns 一个空对象(即 {})
Node.js解释器版本为v6.2.1
V8-引擎版本为5.0.71.52
问题
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.
解决方案 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));