On the scope of this from lambda expression and self = this

Time:2020-10-26

Preface

With the learning of Spring + angular, I began to contact the variable “this”, and encountered some problems in practical use, so I took this as the topic to sort out the content I learned.

1、 This

As the name suggests, it means “this”, “myself”, which means “the current object“. In the previous ThinkPHP, the most common isreturn $this->fetch()That is to return the return value of the fetch method of the current object. This return value is the HTML front-end page that needs to be displayed to the user. So it’s easy to understand that $this means the object to which the method is executed.

2、 Self = this

The difference between “self” and “this” is a question that people think about when they first learn. “From the perspective of English, there is no difference between their translation. They both refer to” his own “… Many people think so. In fact, this is a system variable, which changes dynamically, that is, “relative”. When this is used in object a, this refers to object a, and in object B, this refers to B.
Self is different. In the system, self has no special meaning and is “absolute”. It is a common variable name, which is no different from ABCDEFG (other variable names). Its value completely depends on what value you assign to it: if you assign an object a to self, then no matter where it is called, self is a.

So useself = thisThe purpose ofThe object corresponding to the currently executing codeSave it to prevent the occurrence ofObject change referred to by thisThe situation.

3、 This in lambda expression

When learning the “call between components” section of the “Spring + angular introductory example tutorial”, we need to achieve an effect, that isAfter the addition operation is completed, reinitialize the component and request the database again, so as to update the data in time
On the scope of this from lambda expression and self = this

//Sample code in the tutorial

  constructor(private httpClient: HttpClient, private appComponent: AppComponent ➊) {
  }
  ...
    this.httpClient.post(url, teacher)
      .subscribe(() => {
        console.log ('added successfully ');
        this.appComponent.ngOnInit(); ➋
      }, (response) => {
        console.error ('request error ', response);
      });

    ➊ inject appcomponent directly into the constructor.
    ➋ after the addition is successful, the ngoninit() method of the app component is called again to re request the background data.

I moved the code for the tutorial almost intact.
On the scope of this from lambda expression and self = this

Fill in the information and click Submit
On the scope of this from lambda expression and self = this
Then report an error
On the scope of this from lambda expression and self = this
As you can see, the object has been successfully printed and “post success” has been output, indicating that the process of adding data to the database is correct, and the most important information is“Cannot read property ‘ngOnInit’ of undefined
Cannot read undefined ngoninit method.

However, I have injected the appcomponent object into the constructor, and the object contains the ngoninit method. How can this be undefined?

Later, it was found that the reason lies in this. The code in the tutorial uses the arrow function (lambda expression),
On the scope of this from lambda expression and self = this
And their own code is written as before, using anonymous functions
On the scope of this from lambda expression and self = this

For anonymous functions, this meansThis functionSince this function is not a method of an object, it does not belong to any class. Therefore, if this is used in this anonymous function, the desired object cannot be found.

The special feature of lambda expression is that its “this” refers toThe object that called it。 This refers to whoever calls the lambda expression.
On the scope of this from lambda expression and self = this
Therefore, we only need to change the writing of anonymous function into arrow function, which can perfectly solve the problem of this scope.

Enter the test data again and click Submit. The newly added data will be displayed immediately.
On the scope of this from lambda expression and self = this

The console prints objects correctly
On the scope of this from lambda expression and self = this

This example is used to illustrate this in lambda expression.

4、 Summary

This is a good thing. With it, we can easily call the current object without caring about the name of the object. However, if the concept is not clear, it is easy to use the wrong, resulting in program error. As a beginner, when using this, you need to pay attention to what the “this” you are typing in here. With the gradual enrichment of experience, you can use it skillfully.

Recommended Today

GPS timing products, NTP time calibration, time synchronization server, Beidou time service equipment

GPS timing products, NTP time calibration, time synchronization server, Beidou time service equipment GPS timing products, NTP time calibration, time synchronization server, Beidou time service equipment Long term production and supply of Beijing Zhun Electronic Technology Co., Ltd. ahjzsz summary NTP network time server is a high-tech clock product with high precision, large capacity and […]