Examples of this usage in js
Example 1: the first method to call this is called as a function. It represents the Global Object window
The Code is as follows:
<Script type = "text/javascript">
Function t (){
Alert (this); // this indicates the window object.
}
T ();
</Script>
Example 2: The second method to call this is called as an object property. It represents the object. The onclick attribute of the p element object in the instance
The Code is as follows:
<Html>
<Head>
<Script type = "text/javascript">
Function t (){
Alert (this );
This. style. background = 'green ';
}
Window. onload = function (){
Document. getElementById ('eng'). onclick = t;
}
</Script>
</Head>
<Body>
<P id = "eng"> abcd </p>
</Body>
</Html>
Example 3: The third method to call this is called as a constructor.
The Code is as follows:
<Script type = "text/javascript">
Function dog (){
This. legs = 4;
This. bark = function (){
Alert ("Wang ...");
}
}
Var wangcai = new dog (); // how to create an object. New Function Name ();
Wangcai. bark ();
</Script>
Note:
(1) If you call the dog () function directly instead of creating an object, this is equivalent to the first call, that is, this represents the Global Object window.
(2) js does not have the class concept, but has the object concept;
(3) the object can be created using var = objName {name: 'abc', age: 40}, or through constructors;
(4) What is a constructor? When a common function is called in the form of "new Function Name ()", this function acts as a constructor.
Example 4: Method 4 for calling this-call and apply
The Code is as follows:
<Html>
<Head>
<Script type = "text/javascript">
Window. onload = function (){
Var d = document. getElementById ('Hi ');
If (hi. addEventListener) {// chrome and firefox
Hi. addEventListener ('click', function () {alert (this. id)}, false); // In the w3c model, this points to the DOM object. The result of this. id is hi.
} Else {// ie
Hi. attachEvent ('onclick', function () {alert (this. id)}); // ie8 and ie8. Here this points to the Global Object window. Result this. id: undefined
}
}
</Script>
</Head>
<Body>
<P id = "hi"> hello world </p>
</Body>
</Html>