Definition: This is the object to which the function that contains it belongs when the method is invoked.
Note: This sentence is a bit bite valve, but an extra word is not, the definition is very accurate, we can divide 3 parts to understand it!
1. The function that contains it. 2, as the method is transferred. 3, belongs to the object.
See Example: Function To_green () {this.style.color= "green";} to_green ();
Who does this in the above function refer to? Analysis: The function that contains this is, To_green
The function is called as a method.
The object to which the function belongs is ...? We know that by default, the Window object is all.
Ok,this refers to the Window object, To_green in the execution of the statement will become, window.style.color= "green" This makes the window very angry, because it does not have a style such a property, so the statement does not work. We are changing.
Window.load=function () {var Example=document.getelementbyid ("Example"); Example.onclick=to_green; } What is this?
We know that with the assignment operation, the example object's onclick gets the To_green method, then the function containing this is the onclick, then this is the HTML object referenced by example.
This environment can be changed as the function is assigned to different objects! The following is a complete example:
<script type= "Text/javascript" >
function To_green () {this.style.color= "green"; }
function Init_page () {
var Example=document.getelementbyid ("Example");
Example.onclick=to_green;
}
Window.onload=init_page; </script>
<a href= "#" id= "Example" > click to turn Green </a>
If it is a function inside the object, use this.
function Heightlightrows () {
var rows = document.getElementsByTagName ("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].oldclassname = rows[i].classname;
Rows[i].onmouseover = function () {
AddClass (This, "highlight");
}
Rows[i].onmouseout = function() {
this. ClassName = this. oldclassname;
}
}
}
What is Javascript:this?