Javascript's this point summary (original)

Source: Internet
Author: User

In JavaScript this point has been the front-end Colleague's Heart disease, also is the first choice of the interview questions, now we will summarize the JS in the direction of This. First you need to understand several concepts:

1: the global variable is mounted by default under the Window object
2: in general this is the caller of this point
3:ES6 in the arrow function, this points to the creator, not the caller
4: through call, apply, bind can change the point of this

Let's take a concrete look at

1: when the function is invoked

(non-strict Mode)

1const FUNC =function () {2Console.log ( this);3Const FUNC2 =function () {4Console.log ( this);5         };6Func2 ();//Window7     };8Func ();//Window

(strict Mode)

1' Use strict '2const FUNC =function () {3Console.log ( this);4Const FUNC2 =function () {5Console.log ( this);6         };7Func2 ();//undefined8     };9Func ();//undefined

Combined with rules fourth and one or two: func This function is global and is mounted by default under the window object, this pointer to its caller is window, so the window object is output, but in strict mode, this does not allow pointing to the global variables Window. So the output is undefined (func2 in the function call when the default point to the global window, in fact, This is a flaw in JavaScript design, the correct design is that the internal function of this should be bound to its outer function corresponding to the object, in order to circumvent this design flaw, Smart JavaScript programmers come up with variable substitution methods, which are generally named That. This is the way it will be next.)

2: As Object method

1Const USER = {2 3UserName: ' Xiao Zhang ',4Age:18,5Selfintroduction:function () {6Const STR = ' My name is: ' + this. UserName + ", Age is:" + this. age;7 Console.log (str);8 9Const LOOP =function () {TenConsole.log (' My name is: ' + this. UserName + ", Age is:" + this. age); one             }; a  -Loop ();//My name is: undefined, age is: undefined -  the         } -     }; -  -User.selfintroduction ();//My name is: Xiao zhang, age is: 18

According to our first rule, this points to his caller, the caller of the Selfintroduction () method is user, so within the Selfintroduction () method this points to his parent object, the user, The reason that the loop method output is undefined is the JavaScript design flaw I mentioned above, in which case we usually choose to cache this in the Selfintroduction () method.

1Const USER = {2UserName: ' Xiao Zhang ',3Age:18,4Selfintroduction:function () {5Const STR = ' My name is: ' + this. UserName + ", Age is:" + this. age;6 Console.log (str);7 8Const that= this;9 TenConst LOOP =function () { oneConsole.log (' My name is: ' + that.username + ', age is: ' +that.age); a             }; -  -Loop ();//My name is: Xiao zhang, age is: the  -         } -     }; -  +User.selfintroduction ();//My name is: Xiao zhang, age is:

The Loop's this point is Ideal.

1Const user={2 3UserName: ' Xiao Zhang ',4Age:18,5Selfintroduction:function(){6Const str= ' My name is: ' + this. username+ ", Age is:" + this. age;7 Console.log (str);8         }9     };Ten  oneConst OTHER =user.selfintroduction; aOther ();//My name is: undefined, age is: undefined -  -Const Data={ theUserName: ' Xiao Li ', -Age:19, -     }; -data.selfintroduction=user.selfintroduction; +Data.selfintroduction ();//My name is: Xiao li, age is:

Looking at this code, the Selfintroduction () is assigned to the global variable other, called the other () method, and other is mounted under the Global function window object, There are no username and age properties under the window Object. So the output is Undefined. The second code, which declares the data object, contains the username and the age property, remembering that our second rule normally refers to its caller , and it is understood that data is the caller of the function of Selfintroduction (). So the username and age of data are Output.

3: triggered as an event in HTML

 <  body     >  <  div  id  = "btn"  >  Click I </ div  >  </ body  >  
1         Const Btn=document.getelementbyid (' btn '); 2 3         Btn.addeventlistener (' Click ',function  () {4             console.log (this);  // <div id= "btn" > click me </div> 5         })

In fact, It follows the second rule. in general, this points to its caller, this is the event source that points to the Event.

4:new keyword (constructor)

1     Const  fun=function(userName) {2this         . username=userName; 3     }45     const  user=new fun (' guo Degang ');     6 7     Console.log (user.username);  // Guo Degang

This is not a lot to repeat, the New keyword constructs an object instance, assigned to the user, so username becomes the property of the user Object.

5:ES6 (arrow Function)

1     Const func1= () ={23         console.log (this);   4 5     }; 6 7     //
1Const Data={2UserName: ' principal ',3Selfintroduction:function(){4Console.log ( this);//Object {userName: "headmaster", selfintroduction:function}5 6Const func2= () ={7Console.log ( this);//Object {userName: "headmaster", selfintroduction:function}8             }9 Ten Func2 (); one         } a  -     } -  theData.selfintroduction ();

Everybody's looking at the third rule I said at the beginning:Es6 's Arrow function, this points to the creator, not the caller, fun1 is created under the global function, so this points to the global window, and fun2 is created under Object Data. This points to the data object, so inside of the FUNC2 function this points to the data object, which personally considers the this point of the ES6 arrow function to be an improvement on the JavaScript design flaws I have described above (personal perception).

6: change the direction of this

call, apply, bind these three functions can be artificially changed the function of this point, here is not much to say the difference between the three, in the future blog I will explain in detail the differences between the Three. now, let's take one and give an example.

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

These three methods can be artificially changed the direction of this, the difference is that call, apply will bind the method immediately after the execution, and the Bind method will return an executable Function.

That's a lot to sum up, that's what I said at 4.

1: the global variable is mounted by default under the Window object
2: in general this is the caller of this point
3:ES6 in the arrow function, this points to the creator, not the caller
4: through call, apply, bind can change the point of this

To tell the truth the first time to write a blog, really very disturbed, will someone read my blog? Will it not be written correctly? ...... Think much better, summed up: the bad place is welcome to Correct.

  

      

   

Javascript's this point summary (original)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.