简体   繁体   English

箭头 function 中的“this”是否与箭头 function 之外的“var that = this”中的“that”相同?

[英]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?

Is this a simple rule to remember what a this is inside of an arrow function?这是一个简单的规则来记住箭头 function 中的this是什么?

var that = this;
setTimeout((a, b) => { ... }, 1000);  // the arrow function (a, b) => { ... }

and inside of that arrow function, all the this can be just viewed as the same as that .而在那个箭头function里面,这this都可以看作是一样that

Is this a simple rule to remember how it works?这是一个简单的规则来记住它是如何工作的吗?

Of course, if there is any regular ES5 function inside of the arrow function, then the this inside of that ES5 function is different from that , but will follow the old ES5 way.当然,如果箭头 function 里面有任何常规的 ES5 function,那么this ES5 function 里面的that ,但会跟那个不同。

Update: actually, later on, I found that one better way to think about it might be, just think of the arrow function the same as:更新:实际上,后来,我发现一种更好的思考方式可能是,想想箭头 function 与以下内容相同:

(function() { ... }).bind(this)

that is, the function taking away the this as it currently is, the "lexical this".也就是说,function 删除了当前的this ,即“词法 this”。

The better way to think about the "this" in an arrow function is that it does not have a "this" variable at all, so when you reference "this" inside an arrow function, it works just like any other variable that is not yet defined in that scope such that, it goes one level up in the scope and looks for "this", if it does not find it, it goes another level up in the scope until either it finds a "this" declared or hits the top level scope.考虑箭头 function 中的“this”的更好方法是它根本没有“this”变量,因此当您在箭头 function 中引用“this”时,它就像任何其他变量一样工作尚未在 scope 中定义,这样,它在 scope 中上升一级并寻找“这个”,如果它没有找到它,它在 Z31A1FD140BE4BEF2D11E140BE4BEF2D11E121EC9A18A58Z 中再上升一个级别,直到它找到“这个”顶级 scope。

Hence an arrow function depends on the lexical this.因此,箭头 function 取决于词汇 this。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM