Four cases of this in JavaScript (non-strict mode)
1. When this function is the event handler, this points to the event source.
2. When this function is a constructor, this points to the new object.
3. This refers to the object to which the function belongs.
4, when this function does not belong to the object, this point to the Window object
<! DOCTYPE html> "Utf-8"/> <title></title> "Box" class="Box"style="height:100px, width:100px, background: #f3f3f3;"></div> </body> "Text/javascript">// This//1. This is the event source when this function is the event handler function. document.getElementById ("Box"). onclick =function () {Console.log ( This);//This is Div.box} //2. This is the new object when this function is a constructor. function Person (name) { This. name = name;//This is the new object ZhaosiConsole.log ( This. Name) This. Eat =function () {Console.log ( This. name+"is eatting"); } } varZhaosi =NewPerson ("Zhao Four"); //3, this is where the function of the object is who, this is who. function Person (name) { This. name = name;//It's the new object Liuneng This. Eat =function () {Console.log ( This. name+"is eatting");;//This is who, who calls eat, or calls eat when the front object is who, this is who } } varLiuneng =NewPerson ("Liu Can"); Liuneng.eat ();//When this sentence is executed, the inside of the Eat function is the P1varLaoqi =NewPerson ("Lao Qi"); Laoqi.eat ();//When this sentence is executed, the inside of the Eat function is the P2//4, when this function does not belong to the object, this is the Window object. Global variables are properties of the Window object. function Test () {Console.log ( This);//This is the window .} test ();//The Window object can be omitted, so the sentence is equivalent to window.test (); //a global variable is a property of a Window objectvart ="Bigfoot"; Console.log (WINDOW.T); varobj ={name:"John Doe"} console.log (Window.obj.name); //This transfer is a frequently encountered problem//1), pay attention to distinguish the subordinate object when this function call is located//2), if you do not want to be tortured by this can choose the arrow function in ES6. </script>
Learn from scratch the front end JAVASCRIPT-11, JavaScript base this point four cases