MMi*_*ike 3 javascript foreach object-reference node.js
给出以下代码:
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);
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
0 : Audi
true
undefined
1 : Volvo
true
undefined
2 : Mercedes
true
undefined
Run Code Online (Sandbox Code Playgroud)
我不明白为什么this不引用myObj并返回undefined而不是7.虽然this typeof Object返回true,但我不知道它引用了哪个Object.我只知道this返回一个空对象(即{})
Node.js解释器版本是v6.2.1
V8-Engine版本为5.0.71.52
问题
箭头功能:
一个箭头函数表达式相比具有更短的语法函数表达式和词法结合
this值(不结合其自身的this,arguments,super,或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);Run Code Online (Sandbox Code Playgroud)
解决方案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));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
878 次 |
| 最近记录: |