In javascript, the keyword "this" is a difficult concept to grasp. It refers to different objects in different situations. Let's take a look at the differences between the usage of this in JavaScript?
1. Use the this keyword in the inline mode of HTML element event attributes:
<Div onclick = "method (this)"> element </div>
This indicates the Dom object that triggers the onclick time.
2. Use the this keyword in the event processing function:
<Div id = "elmtDiv"> element </div>
<Script language = "javascript">
Var div = document. getElementById ('mtdiv ');
Div. onclick = function ()
{
// Use this
};
</Script>
Here this refers to the same object as above.
3. this in the function
This in the function indicates the object that calls the function.
Function print (message)
{
This. alert (message );
}
Print ("this is window ");
For example, the print definition of the function above can also be written. Window. print = function () {}. Calling print () is actually the method print on the window object. Therefore, this in print represents the window object. A similar case is the method defined in the constructor:
Function MyClass (name)
{
This. name = name;
This. toString = function (){
Return this. name;
}
}
Var my = new MyClass ('myclass ');
Alert (my. toString ());
This points to the object that calls This method, my.
4. Use this in the class Constructor
Code
Function JSClass ()
{
Var myName = 'jsclass ';
This. m_Name = 'jsclass ';
}
JSClass. prototype. ToString = function ()
{
Alert (myName + ',' + this. m_Name );
};
Var jc = new JSClass ();
Jc. ToString ();
This is the use of this in JavaScript constructor, which is very familiar with other OO languages. However, the member attributes and methods must be referenced using the this keyword. Running the above program will be notified that the myName is not defined. For more information about constructor, see the function definition constructor in Javascript (js.
5. Add the this keyword in the original method to the internal objects of the script engine.
Function. prototype. GetName = function ()
{
Var fnName = this. toString ();
FnName = fnName. substr (0, fnName. indexOf ('('));
FnName = fnName. replace (/^ function /,'');
Return fnName. replace (/(^ \ s +) | (\ s + $)/g ,'');
}
Function foo (){}
Alert (foo. GetName ());
Here this refers to the instance of the class to be added.
6. this in function call
When calling a function as an object method, for example:
Function print ()
{
Alert (this. toString ());
}
Print. apply ('this is first argument ');
Print. call ('this is first argument ');
The first parameter in Function. apply and Function. call is the this object in the Function.