The thisArg
可以提供改变inner this
的回调函数。
未指定thisArg
结果是this
参考Window
在非严格模式下。在严格模式下("use strict";
) 这将是undefined
.
如果你对这个事实感到困惑,那么thisArg
什么也没做使用箭头函数时:
var myObject = { name: 'myObject' };
[1,2].forEach(item => {
console.log(item); // 1, 2
console.log(this === myObject, this); // false Window {}
}, myObject)
这是因为:
箭头函数无法绑定
在箭头函数中,this
指的是最近的范围this
如果没有范围提供,则一直到 Windowthis
价值。它的工作方式就像普通的变量查找,直到某些this
被发现。
为了更好地理解this
see 这个要点 or TS 游乐场.
上下文与正常功能绑定。
var myObject = { name: 'myObject' };
[1,2].forEach(function(item){
console.log(item); // 1, 2
console.log(this === myObject, this); // true {name: "myObject"}
}, myObject)
如果你不指定myObject
此时,this
里面会指向Window
与箭头函数一样。