this of javaScript points to summary (original)

Keywords: Javascript Windows Attribute

In javascript, the direction of this has always been the headache of front-end colleagues and the first choice of interview questions. Now let's summarize the direction of this in js. First, we need to understand several concepts:

1: Global variables are mounted by default under Windows objects
2: In general, this points to its caller
In the arrow function of 3:es6, this points to the creator, not the caller
4: The direction of this can be changed by call, apply and bind

Now let's analyze it in detail.

1:When a function is called

(Non-strict model)

1     const func = function () {
2         console.log(this);
3         const func2 = function () {
4             console.log(this);
5         };
6         func2(); //Window
7     };
8     func();  //Window

(Strict Model)

1     'use strict'
2     const func = function () {
3         console.log(this);
4         const func2 = function () {
5             console.log(this);
6         };
7         func2(); //undefined
8     };
9     func();  //undefined 

Combining the fourth and first two rules: func is global, which is mounted under the window object by default, this points to its caller, that is window, so it outputs the window object, but in strict mode, this is not allowed to point to the global variable window, so the output is undefined (func2 defaults to point to the global window when the function is called directly, in fact, this belongs to Javas The correct way to design cript is that this of internal function should be bound to the object corresponding to its outer function. In order to avoid this design defect, smart JavaScript programmers have come up with a method of variable substitution, which is conventionally known as that. This approach will be discussed later.

2: As an object method

 1     const user = {
 2 
 3         userName: 'Xiao Zhang',
 4         age: 18,
 5         selfIntroduction: function () {
 6             const str = 'My name is:' + this.userName + ",Age is:" + this.age;
 7             console.log(str);
 8 
 9             const loop = function () {
10                 console.log('My name is:' + this.userName + ",Age is:" + this.age);
11             };
12 
13             loop();     //My name is:undefined,Age is:undefined
14 
15         }
16     };
17 
18     user.selfIntroduction();    //My name is:Xiao Zhang,Age is:18

According to our first rule, this points to his caller, and the caller of selfIntroduction () method is user, so inside selfIntroduction () method this points to his parent object, user, and the reason why the loop method outputs undefined is the design flaw of javascript I mentioned above. In this case, we usually choose selfI. This is cached in the ntroduction () method.

 1     const user = {
 2         userName: 'Xiao Zhang',
 3         age: 18,
 4         selfIntroduction: function () {
 5             const str = 'My name is:' + this.userName + ",Age is:" + this.age;
 6             console.log(str);
 7 
 8             const that=this;
 9 
10             const loop = function () {
11                 console.log('My name is:' + that.userName + ",Age is:" + that.age);
12             };
13 
14             loop();     //My name is:Xiao Zhang,Age is:18
15 
16         }
17     };
18 
19     user.selfIntroduction();    //My name is:Xiao Zhang,Age is:18

this is the ideal direction for loop.

 1     const user={
 2 
 3         userName:'Xiao Zhang',
 4         age:18,
 5         selfIntroduction:function(){
 6             const str='My name is:'+this.userName+",Age is:"+this.age;
 7             console.log(str); 
 8         }
 9     };
10 
11     const other =user.selfIntroduction;
12     other();  //My name is:undefined,Age is:undefined
13 
14     const data={
15         userName:'petty thief',
16         age:19,
17     };
18     data.selfIntroduction=user.selfIntroduction;
19     data.selfIntroduction();  //My name is:petty thief,Age is:19

Looking at this code, we assign selfIntroduction () to the global variable other and call other () method. Other is mounted under the global function window object. There are no user Name and age attributes under the window object, so the output is undefined. The second code declares the data object, including the username and age attributes. Remember that our second rule is that this points to its caller in general. As you can see, data is the caller of selfIntroduction (), so it outputs the userName and age of data.

3: Triggered as an event in html

<body>

    <div id="btn">Click on me</div>

</body>
1         const btn=document.getElementById('btn');
2 
3         btn.addEventListener('click',function () {
4             console.log(this);  //<div id="btn">Click on me</div>
5         })

In this case, the second rule is followed. In general, this points to its caller, and this points to the event source, which is event.

4:new keyword (constructor)

1     const  fun=function(userName){
2         this.userName=userName;
3     }
4 
5     const  user=new fun('Guo Degang');    
6 
7     console.log(user.userName);  //Guo Degang

The new keyword constructs an object instance and assigns it to the user, so userName becomes the attribute of the user object.

5:es6 (arrow function)

1     const func1=()=>{
2 
3         console.log(this);  
4 
5     };
6 
7     func1(); //Window 
 1     const data={
 2         userName:'Principal',
 3         selfIntroduction:function(){
 4             console.log(this); //Object {userName: "Principal", selfIntroduction: function}
 5 
 6             const func2=()=>{
 7                 console.log(this);  //Object {userName: "Principal", selfIntroduction: function}
 8             }
 9 
10             func2();
11         }
12 
13     }
14 
15     data.selfIntroduction();

In the arrow function of es6, this points to the creator, not the caller, fun1 creates under the global function, so this points to the global window, while fun2 creates under the object data, this points to the data object, so this points to the data object within the func2 function. Personally, I think the arrow function of ES6 points to the data object. Said the improvement of javascript design flaws (personal recognition).

6: Change the direction of this

call, apply, and bind are three functions that can be artificially altered by this function, so I won't say much about the differences between them here. I will explain the differences in detail in my blog in the future. Now let's take an example.

1 const func=function(){
2     console.log(this);
3 };
4 
5 func(); //window
6 
7 func.apply({userName:"Guo Degang"});  //Object {userName: "Guo Degang"}

All three methods can change the direction of this artificially. The difference is that call and apply will bind this method to execute immediately, while the bind method will return an executable function.

To sum up, that's the four points I started with.

1: Global variables are mounted by default under Windows objects
2: In general, this points to its caller
In the arrow function of 3:es6, this points to the creator, not the caller
4: The direction of this can be changed by call, apply and bind

To tell you the truth, the first time to write a blog, it is really quite nervous, will anyone read my blog? Can you write incorrectly? Think much better, sum up: bad places welcome correction.

Posted by miracle_potential on Tue, 11 Jun 2019 14:27:49 -0700