It seems that this sentence is quite reasonable to know the gains and losses in the eyes of others.
Demo 1:
If it is a global function, this is equivalent to a window object. Various attributes or methods defined in the function can be accessed outside the function, provided that the function needs to be called.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
// Use this in the function
Function (){
If (this = window ){
Alert ("this = window ");
This. fieldA = "I'm a field ";
This. methodA = function (){
Alert ("I'm a function ");
}
}
}
A (); // If method a is not called, the attributes defined in it will not be obtained.
Alert (window. fieldA );
MethodA ();
</Script>
Demo 2:
If you use the new method to instantiate an object, this is not equal to the window object, and this points to the instance of function.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
// Use this 2 in the function
Function (){
If (this = window ){
Alert ("this = window ");
}
Else {
Alert ("this! = Window ");
}
This. fieldA = "I'm a field ";
}
Var B = new ();
Alert (B. fieldA );
</Script>
Demo 3:
You can use this to obtain the instance of the source object using prototype extension. Private fields cannot be obtained through prototype chain.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
// Use this 3 in the function
Function (){
This. fieldA = "I'm a field ";
Var privateFieldA = "I'm a var ";
}
A. prototype. ExtendMethod = function (str ){
Alert (str + ":" + this. fieldA );
Alert (privateFieldA); // Error
};
Var B = new ();
B. ExtendMethod ("From prototype ");
</Script>
Demo 4:
Whether directly referencing a function or instantiating a function, this in the returned closure function is directed to the window
Copy codeThe Code is as follows:
<Script type = "text/javascript">
// Use this 4 in the function
Function (){
Alert (this = window );
Var that = this;
Var func = function (){
Alert (this = window );
Alert (that );
};
Return func;
}
Var B = ();
B ();
Var c = new ();
C ();
</Script>
Demo 5:
Using this in HTML generally indicates the element itself
Copy codeThe Code is as follows:
<Div onclick = "test (this)" id = "div"> Click Me </div>
<Script type = "text/javascript">
Function test (obj ){
Alert (obj );
}
</Script>
Demo 6:
Register events under IE and Firefox (Chrome). this points to the window and the element itself, respectively.
Copy codeThe Code is as follows:
<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.tar get = this );
}, False );
}
</Script>
The above is my summary of the different use cases of this in javascript. There may be other situations, which will be added later.