JS in the this point is very important to understand JS in this point is every learning JS people must learn the knowledge point, today is nothing, just summed up JS in this common usage, like can see:
1. Global scope or normal function
ThisPoint to Global object
window。
1 //Direct Printing2Console.log ( This)//window3 4 //function declaration Functions5 functionBar () {Console.log ( This)}6Bar ()//window7 8 //function declaration functions assigned to variables9 varBar =function() {Console.log ( This)}TenBar ()//window One A //self-executing functions -(function() {Console.log ( This)})();//window
2. In the method call, who calls the this point who
1{Console.log ( This)}2 }3Person.run ()// Person4 5 //Event Bindings6 varBTN = Document.queryselector ("button")7Btn.onclick =function () {8Console.log ( This)//btn9 }Ten //Event Monitoring One varBTN = Document.queryselector ("button") ABtn.addeventlistener (' click ',function () { -Console.log ( This)//btn - }) the - //the Ajax of jquery - $.ajax ({ -Self This, +Type: "Get", - Url:url, +Asynctrue, ASuccessfunction(res) { atConsole.log ( This)//This points to the object in the incoming $.ajxa () -Console.log (self)//window - } - }); - //here, the code is abbreviated as $.AJAX (obj), this points to obj, and this points to the window in obj, because in the success method, the exclusive obj calls itself, so this points to obj
3. In a constructor or constructor prototype object ThisA pointer to an instance of the constructor
1 //do not use new to point to window2 functionPerson (name) {3Console.log ( This)//window4 This. Name =name;5 }6Person (' inwe ')7 //using the new8 functionPerson (name) {9 This. Name =nameTenConsole.log ( This)//people OneSelf = This A } - varPeople =NewPerson (' Iwen ') -Console.log (self = = = people)//true the //here new changes the this point, which points to the instance object of person by window people
Day 149th: The point of this in JavaScript