Javascript this usage Summary

Source: Internet
Author: User

This is an important concept in object-oriented language. In large languages such as JAVA and C #, this is fixed to the current object at runtime. However, in javascript, due to the dynamic nature of javascript (interpretation and execution, there are also simple pre-compilation processes), the point of this is determined at runtime. This feature brings us confusion while also bringing programming freedom and flexibility. Combined with the apply (call) method, JS can become exceptionally powerful.
2. this variable
In JavaScript, this usually points to the function we are executing, or to the object to which the function belongs (runtime ). When we define the function doSomething () in the page, its owner is the page, or the window object (or global Object) in JavaScript ). For an onclick attribute, it is owned by the HTML element to which it belongs. this should point to this HTML element.
2.1 this variation in several common scenarios
Function example
Function doSomething ()
{
Alert (this. navigator); // appCodeName
This. value = "I am from the Object constructor ";
This. style. backgroundColor = "#000000 ";
}
1. When (A) is directly called as A common function, this points to the window object.
2. (B) when triggered as a control event
1) inline event registration. Write the event directly in HTML code (<element
Onclick = "doSomething ()">). this points to the window object.
2) Traditional event registration (DHTML mode ).
Such as element. onclick = doSomething; this points to the element object.
3) <element onclick = "doSomething (this)"> as a parameter, you can point
3. When (C) is used as an object, this points to the current object. Shape: new doSomething ();
4. (D) when the apply or call method is used, this points to the passed object.
Such as var obj ={}; doSomething. apply (obj, new Array ("nothing"); // this à obj

Next I will explain how to use this in event processing, and then I will add some examples related to this.
Owner
The question we will discuss in the next article is: What does this refer to in the doSomething () function?
Javascript code
Function doSomething (){
This. style. color = '# cc0000 ';
}
Function doSomething (){
This. style. color = '# cc0000 ';
}
In JavaScript, this usually points to the function itself that we are executing (the Translator's note: The owner represents the content that this points to), or to the object to which the function belongs. When we define the function doSomething () in the page, its owner is the page, or the window object (or global Object) in JavaScript ). For an onclick attribute, it is owned by the HTML element to which it belongs. this should point to this HTML element.
This "ownership" is an object-oriented method in JavaScript. You can view more information in Objects as associative arrays.
 
If we execute doSomething () without any preparation, this keyword will point to the window, and this function tries to change the style. color of the window. Because the window does not have a style object, this function will unfortunately fail to run and generate JavaScript errors.
Copying
Therefore, if we want to make full use of this, we have to note that the function using this should be owned by the correct HTML element. In other words, we should copy this function to our onclick attribute. Traditional event registration will care about it.
Javascript code
Element. onclick = doSomething;
Element. onclick = doSomething;
This function is completely copied to the onclick attribute (now a function ). Therefore, if the event handler is executed, this will point to the HTML element and the color of the element will be changed.
 
This method enables us to copy this function to multiple event handler. Each time this is directed to the correct HTML element:
 
In this way, you can use this to the maximum extent. Every time you execute this function, the HTML elements pointed to by this correctly respond to events. These HTML elements have a copy of doSomething.
Referring
However, if you use inline event Registry (inline event registration)
Javascript code
<Element onclick = "doSomething ()">
<Element onclick = "doSomething ()">
You cannot copy this function! However, this difference is critical. The onclick attribute does not contain actual functions. It is just a function call.
Javascript code
DoSomething ();
DoSomething ();
Therefore, it will declare "go to doSomething () and execute it ". When we reach doSomething (), this keyword points to the global window object again, and the function returns an error message.
 
The difference
If you want to use this to point to the HTML element RESPONSE event, you must ensure that the keyword this is written in the onclick attribute. In this case, it directs to the HTML element registered by event handler.
Javascript code
Element. onclick = doSomething;
Alert (element. onclick)
Element. onclick = doSomething;
Alert (element. onclick)
You will get
Javascript code
Function doSomething (){
This. style. color = '# cc0000 ';
}
Function doSomething (){
This. style. color = '# cc0000 ';
}
As you can see, the this keyword is displayed in the onclick function, so it points to the HTML element.
However, if
Javascript code
<Element onclick = "doSomething ()">
Alert (element. onclick)
<Element onclick = "doSomething ()">
Alert (element. onclick)
You will get
Javascript code
Function onclick (){
DoSomething ()
}
Function onclick (){
DoSomething ()
}
This is just a reference to the doSomething () function. This keyword does not appear in the onclick function, so it does not point to HTML elements.
Example-copy
In the following example, this is written to The onclick function:
Javascript code
Element. onclick = doSomething
Element. addEventListener ('click', doSomething, false)
Element. onclick = function () {this. style. color = '# cc0000 ';}
<Element onclick = "this. sytle. color = '# cc0000';">
Element. onclick = doSomething
Element. addEventListener ('click', doSomething, false)
Element. onclick = function () {this. style. color = '# cc0000 ';}
<Element onclick = "this. sytle. color = '# cc0000';">
Example-Reference
In the following cases, this points to window:
Javascript code
Element. onclick = function () {doSomething ()}
Element. attachEvent ('onclick', doSomething)
<Element onclick = "doSomething ()">
Element. onclick = function () {doSomething ()}
Element. attachEvent ('onclick', doSomething)
<Element onclick = "doSomething ()">
Note the appearance of attachEvent. The main drawback of Microsoft event registration model is that attachEvent () creates a reference pointing to a function instead of copying it. Therefore, it is sometimes impossible to know which HTML is processing the event.
Combined Use
When using inline event registration, you can send this to the function so that it can be used properly:
Javascript code
<Element onclick = "doSomething (this)">
Function doSomething (obj ){
// This appears in event handler and is sent to function
// Obj points to the HTML element, so you can:
Obj. style. color = '# cc0000 ';
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.