Preface
The usage of this in JavaScript has been described in more detail in the network. You can refer to the reference materials and networks in this article. This article, combined with network collection, tries to elaborate on the usage of this in JavaScript in a simple way and hopes to help you quickly understand the usage of this in JavaScript.
Body
1. this usage example
Copy codeThe Code is as follows:
Window. color = "red ";
Var o = {color: "blue "};
Function sayColor (){
Alert (this. color );
}
SayColor (); // "red"
O. sayColor = sayColor;
O. sayColor (); // "blue"
2. Easy to understand this usage
Where does this point:
This is the context object, or the current scope of the function in which this is located.
A piece of instance code immediately understands:
Copy codeThe Code is as follows:
Var fun = function (){
Console. log (this );
}
Fun (); // console: window. The execution context of fun is window, that is, the current scope of this function (fun () when it is called is window.
New fun (); // console: fun. The execution context of fun is within the fun object, that is, the current scope of the function (fun () in which this is located is within the fun object.
3. A special case of this usage
(1) situation:
Copy codeThe Code is as follows:
<Input type = "button" id = "aButton" value = "demo" onclick = "demo ()"/>
<Script type = "text/javascript">
Function demo (){
This. value = Math. random ();
}
</Script>
After clicking this button, you will find that the value of the button has not changed.
Cause: When this code runs, this points to the window object.
Copy codeThe Code is as follows:
<Input type = "button" id = "aButton" value = "demo"/>
<Script type = "text/javascript">
Var button = document. getElementById ("aButton ");
Function demo (){
This. value = Math. random ();
}
Button. onclick = demo;
</Script>
After clicking this button, the program can be executed normally.
(2) Cause explanation:
Copy codeThe Code is as follows:
<Input type = "button" id = "aButton" value = "demo"/>
<Script type = "text/javascript">
Var button = document. getElementById ("aButton ");
Function demo (){
This. value = Math. random ();
}
Button. onclick = demo;
Alert (button. onclick );
</Script>
The output is as follows:
Copy codeThe Code is as follows:
Function demo (){
This. value = Math. random ();
}
Copy codeThe Code is as follows:
<Input type = "button" id = "aButton" value = "demo" onclick = "demo ()"/>
<Script type = "text/javascript">
Var button = document. getElementById ("aButton ");
Function demo (){
This. value = Math. random ();
}
Alert (button. onclick );
</Script>
The output is as follows:
Copy codeThe Code is as follows:
Function onclick (){
Demo ();
}