Really to explain this thing, only to find that it is not so simple, spent some time, wrote a few small demo, let us come to a probe. Well, to artificial mirror, know gains and losses, it seems that this sentence is very reasonable. Royal Casino
If it is a global function, this is equivalent to the Window object, and the various properties or methods defined in the function can be accessed outside the function, provided that the function needs to be called.
<script type= "Text/javascript" > //Use this function in function a () { if (this = = window) { alert (" this = = window "); This.fielda = "I ' m a field"; This.methoda = function () { alert ("I ' m a function"); }}} A (); If you do not call the A method, the attribute defined inside will not get alert (Window.fielda); MethodA (); </script>
If you use new to instantiate an object, this is not equal to the Window object, which points to the instance of function A:
<script type= "Text/javascript" > //Use the second function A () { if (this = = window) { alert ("This = = Window"); } else { alert ("This! = Window"); } This.fielda = "I ' m a field"; } var B = new A (); alert (B.fielda); </script>
Use the prototype extension method to get an instance of the source object using this, and the private field cannot be obtained through the prototype chain:
<script type= "Text/javascript" > //Use this three function a () { This.fielda = "I ' m a field" in function); var Privatefielda = "I ' m a var"; } A.prototype.extendmethod = function (str) { alert (str + ":" + This.fielda); alert (Privatefielda); Error }; var B = new A (); B.extendmethod ("from Prototype"); </script>
Whether you are referencing functions directly or instantiating a function, the this in the enclosing function returned is a pointer to window.
<script type= "Text/javascript" > //Use the four function A () { alert (this = = window) in function; var = this; var func = function () { alert (this = = window); alert (that); }; return func; } var B = A (); b (); var C = new A (); C ();</script>
The use of this in HTML typically represents the element itself:
<div onclick= "Test (This)" id= "div" >click me</div> <script type= "Text/javascript" > function test (obj) { alert (obj); } </script>
Register the event under IE and Firefox (Chrome), which points to window and the element itself:
<div id= "div" >click me</div> <script type= "Text/javascript" > var div = document.getElementById ("div"); if (div.attachevent) { div.attachevent ("onclick", function () { alert (this = = window); var e = event; Alert (E.srcelement = = this); }) ; if (div.addeventlistener) { div.addeventlistener ("click", Function (e) { alert (this = = window); e = e; Alert (E.target = = this); }, False); } </script>
A few examples to help you understand the use of JavaScript this