Summary of this usage in JavaScript

Source: Internet
Author: User
This is an important concept in object-oriented languages, in large languages such as java,c#, this fixed point to the current object at run time. However, in JavaScript, because of the dynamic nature of JavaScript (interpretation, and of course there is a simple precompilation process), this point is not determined at run time. This feature brings us confusion at the same time also brings the freedom of programming and flexibility, combined with the Apply (call) method, can make JS become unusually powerful.
2. The change of this
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 it is a Window object (or Global object) in JavaScript. For an OnClick property, which is owned by the HTML element to which it belongs, this should point to the HTML element.
2.1 Variations of this in several common scenarios
Examples of functions
function dosomething ()
{
alert (this.navigator); appCodeName
This.value = "I am from the Object constructor";
This.style.backgroundColor = "# 000000";
}
1. (A) when called directly as a normal function, this points to the Window object.
2. (B) when triggered as a control event
1) inline event registration inline events registration. Writes the event directly in the HTML code (<element
Onclick= "dosomething ()" >), this points to the Window object.
2) Traditional Event registration traditional events Registration (DHTML method).
Shaped like Element.onclick = dosomething; This point points to the element object
3) <element onclick= "dosomething (This)" > as parameter Pass can point to element
3. (C) when used as an object, this points to the current object. Shaped like: New DoSomething ();
4. (D) When using the Apply or call method, this points to the object being passed.
Shaped like: Var obj={}; Dosomething.apply (Obj,new Array ("nothing");//thisàobj


Let me explain how to use this in event handling, and then I'll append some examples of this.
Owner
The question we will discuss in the next article is what this refers to in the function dosomething ().
JavaScript code
function dosomething () {
This.style.color = ' #cc0000 ';
}
function dosomething () {
This.style.color = ' #cc0000 ';
}
In JavaScript, this usually points to the function we are executing (the translator: Using owner to represent the content pointed to by this), or to the object to which the function belongs. When we define the function dosomething () in the page, its owner is the page, or it is a Window object (or Global object) in JavaScript. For an OnClick property, which is owned by the HTML element to which it belongs, this should point to the HTML element.
This "ownership" is a way of object-oriented in JavaScript. You can view some more information in the objects as associative arrays.

If we execute dosomething () without any more preparation, the This keyword points to window and the function attempts to change the style.color of the window. Because window does not have a style object, this function will unfortunately fail to run and produce JavaScript errors.
Copying
So if we want to take full advantage 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 property. Traditional event registration will care about it.
JavaScript code
Element.onclick = dosomething;
Element.onclick = dosomething;
This function is fully copied to the OnClick attribute (now a function). So if this event handler is executed, this will point to the HTML element, and the color of the element is changed.

This method allows us to replicate this function to multiple event handler. Each time this will point to the correct HTML element:

So you can use this for maximum. Whenever this function is executed, the HTML elements that this point to are correctly responsive to events, which have a copy of DoSomething ().
Referring
However, if you use inline event registration (inline events registration)
JavaScript code
<element onclick= "dosomething ()" >
<element onclick= "dosomething ()" >
You will not be able to copy the function. But this difference is very critical. The OnClick property does not contain the actual function, just a function call.
JavaScript code
DoSomething ();
DoSomething ();
Therefore, it declares "go to DoSomething () and execute it". When we arrive at DoSomething (), the This keyword again points to the global Window object, and the function returns an error message.

The difference
If you want to use this to point to an event that the HTML element responds to, you must ensure that the This keyword is written in the onclick attribute. Only in this case does it point to the HTML element that the event handler is registered with.
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, this keyword is displayed in the OnClick function, so it points to an HTML element.
But if you do
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. The This keyword does not appear in the OnClick function, so it does not point to an HTML element.
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 disadvantage of Microsoft event registration model is that attachevent () creates a reference to a function, rather than copying it. So it is sometimes impossible to know which HTML is handling the event.
Combined use
When registering with an inline event, you can send this to a function so that it can be used normally:
JavaScript code
<element onclick= "dosomething (This)" >
function dosomething (obj) {
This appears in the event handler and is sent to the function
Obj points to HTML elements, so you can do this:
Obj.style.color = ' #cc0000 ';
}
Detailed Source reference: http://www.jb51.net/article/16863.htm

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.