简体   繁体   English

对箭头功能中的“this”感到困惑

[英]Confused about “this” in arrow function

I've seen a lot of discussion on this topic, and I've read through numerous articles, but I'm still confused about what this refers to in arrow functions. 我已经看到了很多的讨论这个话题,我已经通过了大量的文章阅读,但我仍然感到困惑的是什么this是指在箭头的功能。

I seem to be getting run-time errors associated with the following code (simplified): 我似乎得到与以下代码相关的运行时错误(简化):

export class Foo implements OnInit {
myProp: string;
myKeys: Array<any> = [];
mySubKeys: Array<any> = [];
@Input myObj;

. . . 

ngOnInit() {

this.myKeys = Object.keys(this.myObj); 
this.myKeys.forEach((key) => {
    this.myProp = key;
    this.mySubKeys = Object.keys(this.myObj[key]);
    this.mySubKeys.forEach((subkey) => { . . .  
. . . 

The error happens at this.myProp = key where the debugger complains that this is undefined. 错误发生在this.myProp = key ,调试器抱怨this是未定义的。

My confusion is that for arrow functions I understood that this refers to the this preceding the scope in which the arrow function is called. 我的困惑是,对于箭头函数,我理解this是指在调用箭头函数的范围之前的this In this case, wouldn't the preceding scope be the class scope, and therefore shouldn't this.myProp be defined? 在这种情况下,前面的范围不是class范围,因此不应该定义this.myProp吗?

I tried changing the arrow function to forEach(function(key) { . . . but got different errors. 我尝试将箭头功能更改为forEach(function(key){...但有不同的错误。

Finally, if the this inside the arrow function doesn't refer to the class this then how do I refer to the class this and associated class properties (such as myProp ) inside the arrow function? 最后,如果this箭头函数内部不参考class this ,然后我怎么参考class this和相关的class属性(如myProp )箭头函数内?

The reason for this is that the value of this in a function depends on how the function is called. 原因是函数中this的值取决于函数的调用方式。

At it's most basic level if the function is called as this.myKeys.forEach() , the value of this is the calling context which in this case is myKeys 在它的如果函数被称为最基层this.myKeys.forEach()this是在这种情况下是调用上下文myKeys

In all cases however it isn't going to be myKeys , so this.myProp & this.mySubKeys is not going to return value , it's going to return undefined or raise an error. 但是在所有情况下它都不会是myKeys ,所以this.myProp & this.mySubKeys不会返回value ,它会返回undefined或引发错误。

This instability of this is an incredibly common problem in Javascript that has affected it since the early days. 这种不稳定性是Javascript中一个非常普遍的问题,从早期开始就影响了它。

In ES5 there are a number of methods we can use to stabilize the value of this . ES5也有一些我们可以用稳定的值的方法this One common solution is to assign this to another variable at the top, usually called self , and then always use self in the function body, like so: 一个常见的解决方案是将它分配给顶部的另一个变量,通常称为self ,然后在函数体中始终使用self ,如下所示:

ngOnInit() {


   this.myKeys = Object.keys(this.myObj) {

    let self = this; // declare the variable to refer class object
    this.myKeys.forEach((key) => {
        self.myProp = key;
        self.mySubKeys = Object.keys(this.myObj[key]);
        self.mySubKeys.forEach((subkey) => { . . .  
   . . . 

Hope this will help! 希望这会有所帮助!

The this in the code you expose should work as you intend to. 您公开的代码中的这个应该按照您的意图工作。 I think your problem comes from this line: 我认为你的问题来自这一行:

this.myKeys = Object.keys(this.myObj) {

There is an opening { when it should be just a close ; 有一个开口{当它应该只是一个关闭; .

this.myKeys = Object.keys(this.myObj);

The code should look like: 代码应如下所示:

ngOnInit() {
    this.myKeys = Object.keys(this.myObj);
    this.myKeys.forEach((key) => {
        this.myProp = key;
        this.mySubKeys = Object.keys(this.myObj[key]);

Edit: 编辑:

Adding demo to try the this is working: https://stackblitz.com/edit/stackoverflow-mykeys-demo 添加演示试试这个是有效的: https//stackblitz.com/edit/stackoverflow-mykeys-demo

Note that the Input() has to have the () too. 请注意, Input()也必须具有()。

From MDN : 来自MDN:

An arrow function does not have its own this. 箭头功能没有自己的功能。 The this value of the enclosing lexical scope is used; 使用封闭词法范围的该值; arrow functions follow the normal variable lookup rules. 箭头函数遵循常规变量查找规则。 So while searching for this which is not present in current scope they end up finding this from its enclosing scope. 因此,在搜索当前范围中不存在的内容时,他们最终会从其封闭范围中找到它。

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

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