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);
我得到以下输出:
<$ p $奥迪
真
undefined
1:沃尔沃
真
2:奔驰
true
undefined
在这里我不明白为什么 Node.js解释器版本是v6。 2.1 b 问题 箭头函数: 箭头函数表达式与函数表达式和词法相比,语法较短绑定 解决方案1 $ c $ function code>不引用myObj,并返回undefined而不是7.
这个类型的Object
返回true,我不知道它引用了哪个对象。我只知道这个
返回一个空的Object(即{})
$ b V8-Engine版本是5.0.71.52
这个
值(不绑定自己的 这个
, arguments
, super
,或者 new.target
)。箭头功能总是匿名。
$ b $ p 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 使用闭包 Given following code: I get following output: Where I don't understand why Node.js interpreter version is v6.2.1 V8-Engine version is 5.0.71.52 Problem An arrow function expression has a shorter syntax compared to function expressions and lexically binds the Solution 1 Use
Solution 2 Use a closure
这篇关于array.forEach的thisArg不按预期引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<
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
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. {})
this
value (does not bind its own this
, arguments
, super
, or new.target
). Arrow functions are always anonymous.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);
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));