这个问题可能已经被问到了。从文档中,我们可以将 a 传递thisVariable给 map 函数。
var foo=[1,2].map(function(){return this.length},[2,4]); // [2,2]
Run Code Online (Sandbox Code Playgroud)
然而,ES6 中的这种语法返回了其他东西
var foo=[1,2].map(_ => this.length ,[2,4]); // [0,0]
Run Code Online (Sandbox Code Playgroud)
[0,0]返回的是什么?
箭头函数保留thisValue调用函数中作用域内的那个,它不能被重置。所以thisValue传递给的参数map()被忽略。
因此,当您使用 时this.length,它使用this来自调用上下文的值。如果您在顶层执行代码(例如在 Javascript 控制台中)this == window,那么您将得到 的结果window.length,即0。
| 归档时间: |
|
| 查看次数: |
1330 次 |
| 最近记录: |