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

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

Nin*_*olz 7

问题

箭头功能:

一个箭头函数表达式相比具有更短的语法函数表达式和词法结合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)

  • 好吧我想在node.js中,没有窗口对象,可能是因为它确实在服务器上而不是在浏览器中运行.我发现[this](http://stackoverflow.com/questions/19849136/does-node-js-have-equivalent-to-window-object-in-browser)表明在node.js中有一个Object全局哪个是最接近窗口对象的.:)万一你有兴趣. (2认同)
  • @ooronning在某些方面.标准的全局JavaScript API可以通过`global`获得.`process`包含所有Node扩展.所以你可能会认为它就像`document`,但它确实是它自己的东西. (2认同)