Briefly describe the use of this
The fact that this is determined by the called method makes this can be changed, thus adding a dynamic, variability to the function, which makes it more flexible. At present, because of limited working experience, temporary summary
The use of this in five cases, there will be time to understand the application of this in depth from the ECMA specification.
1. Situation One: called in the form of a function, this is the window
1 Console.log (this); // window 2 function Fu () {3 console.log (this); 4 }5 fu (); window
2. Situation Two: called in the form of a method, this is the object that invokes the method
1 var obj ={name: ' This '}; 2 function foo () {3 console.log (this); 4 }5 obj.foo=foo; 6 Obj.foo (); // Output obj {name: ' This ', foo: [Function:foo]}
3. Scenario three: Invoking in the form of a constructor function
1 functionD () {2 This. Name = ' Test ';3 This. Age =18;4Console.log ( This);5 }6 varD =NewD ();//Output D Object7D.name = ' Hewenfeng ';8D ();//window9Console.log (d);//Output D Object
4. Scenario four: Calling in the global scope
1 console.log (this); window
5. Situation five: In the response function, to whom to bind the event, this is who.
1<! DOCTYPE html>234<meta charset= "UTF-8" >5 67<body>8<div id= "B" onclick= "Console.log (This)" >9<div>Ten</body> One A output: div element itself - -<! DOCTYPE html> the - -<meta charset= "UTF-8" > - +<body> -<div id= "B" onclick= "Console.log (This)" > +<div> A at<script type= "Text/javascript" > - varC=document.getelementbyid ("B"); -c.onclick=function() {Console.log (1)} - -</script> -</body> in -Output: 1 to the way the onclick is bound overrides the inline event binding. You can also output this in C.onclick to know that this represents the div element itself. + -<! DOCTYPE html> the * $<meta charset= "UTF-8" >Panax Notoginseng -<body> the<div id= "B" onclick= "Console.log (This)" > +<div> A the<script type= "Text/javascript" > + varC=document.getelementbyid ("B"); -c.onclick=function() {Console.log (1)} $C.addeventlistener ("click",function() {alert (' 2 ')},false) $</script> -</body> - theOutput: 1, Pop
AddEventListener does not overwrite C.onclick bound functions, nor does it naturally overwrite the inline onclick,addeventlistener, which is bound to the event handler in an overlay.
Just like using AddEventListener to bind a few event handlers) You can also output this in the event handler of AddEventListener to know that this represents the div element itself.
Summary of the application of this in JS