[英]Is it identical, that a “this” in an arrow function, is the same as a “that” as in “var that = this” outside of that arrow function?
这是一个简单的规则来记住箭头 function 中的this
是什么?
var that = this;
setTimeout((a, b) => { ... }, 1000); // the arrow function (a, b) => { ... }
而在那个箭头function里面,这this
都可以看作是一样that
。
这是一个简单的规则来记住它是如何工作的吗?
当然,如果箭头 function 里面有任何常规的 ES5 function,那么this
ES5 function 里面的that
,但会跟那个不同。
更新:实际上,后来,我发现一种更好的思考方式可能是,想想箭头 function 与以下内容相同:
(function() { ... }).bind(this)
也就是说,function 删除了当前的this
,即“词法 this”。
考虑箭头 function 中的“this”的更好方法是它根本没有“this”变量,因此当您在箭头 function 中引用“this”时,它就像任何其他变量一样工作尚未在 scope 中定义,这样,它在 scope 中上升一级并寻找“这个”,如果它没有找到它,它在 Z31A1FD140BE4BEF2D11E140BE4BEF2D11E121EC9A18A58Z 中再上升一个级别,直到它找到“这个”顶级 scope。
因此,箭头 function 取决于词汇 this。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.