[Translation] this keyword about JavaScript

Source: Internet
Author: User

One of the most powerful JavaScript keywords is this. Unfortunately it is hard to use if you don't exactly know how it works.

In JavaScript, this is one of the most important keywords. This post tells you how to make good use of this.

Below I explain how to use it in event handling. Later on I'll add some information about other uses of this.

Next I will first explain how to use it in event handling (event processing), and then talk about other usage of this.

Owner

The question that we'll discuss for the remainder of the page is: What does this refer to in the function doSomething ()?

Let's take a look at what this actually points to (refer to) in the doSomething () function?

function doSomething() {   this.style.color = '#cc0000';}

In JavaScript this always refers to the "owner" of the function we're re executing, or rather, to the object that a function is a method. when we define our faithful function doSomething () in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. an onclick property, though, is owned by the HTML element it belongs.

This in JavaScript always points to the owner of the function being executed. Or, it is a method that points to the function object. When defining the function doSomething () in the page, its owner is the page. More specifically, it is a JavaScript window object (Global object ). The onclick attribute belongs to all HTML elements.

This "ownership" is the result of JavaScript's object oriented approach. See the Objects as associative arrays page for some more information.

This ownership of all relationships is caused by the JavaScript OO (Object-Oriented) feature. For more information, see associating objects with arrays.

------------ window --------------------------------------|                                          /            ||                                           |            ||                                          this          ||   ----------------                        |            ||   | HTML element | <-- this         -----------------  ||   ----------------      |           | doSomething() |  ||               |         |           -----------------  ||          --------------------                          ||          | onclick property |                          ||          --------------------                          ||                                                        |----------------------------------------------------------

If we execute doSomething () without any more preparation the this keyword refers to the window and the function tries to change the style. color of the window. since the window doesn' t have a style object the function fails miserably and produces JavaScript errors.

Here, when doSomething () is executed, the keyword "this" points to window. this function will change the style. color of window. Window does not have the style object, so this function will cause JavaScript errors.

Copying

So if we want to use this to its full extent we have to take care that the function that uses it is "owned" by the correct HTML element. in other words, we have to copy the function to our onclick property. traditional event registration takes care of it.

Therefore, if you want to make good use of this, continue to look at it. As in the previous example used in a function, this points to the HTML element to which it belongs. That is to say, there is a function copy pointing to the onclick attribute. Let's look at the registration of traditional events.

element.onclick = doSomething;

The function is copied in its entirety to the onclick property (which now becomes a method). So if the event handler is executed this refers to the HTML element and its color is changed.

The function is its entire copy, pointing to the onclick attribute (now the method is changed ). Therefore, when event processing is executed, this points to the HTML element and changes the color.

------------ window --------------------------------------|                                                        ||                                                        ||                                                        ||   ----------------                                     ||   | HTML element | <-- this         -----------------  ||   ----------------      |           | doSomething() |  ||               |         |           -----------------  ||          -----------------------          |            ||          |copy of doSomething()|  <-- copy function    ||          -----------------------                       ||                                                        |----------------------------------------------------------

The trick is of course that we can copy the function to several event handlers. Each time this will refer to the correct HTML element:

In this way, we can copy functions to process multiple events. Each time this points to the correct HTML element:

------------ window --------------------------------------|                                                        ||                                                        ||                                                        ||   ----------------                                     ||   | HTML element | <-- this         -----------------  ||   ----------------      |           | doSomething() |  ||               |         |           -----------------  ||          -----------------------          |            ||          |copy of doSomething()|  <-- copy function    ||          -----------------------          |            ||                                           |            ||   -----------------------                 |            ||   | another HTML element| <-- this        |            ||   -----------------------     |           |            ||               |               |           |            ||          -----------------------          |            ||          |copy of doSomething()|  <-- copy function    ||          -----------------------                       ||                                                        |----------------------------------------------------------

Thus you use this to the fullest extent. each time the function is called, this refers to the HTML element that is currently handling the event, the HTML element that "owns" the copy of doSomething ().

Each time a function is called, this points to the HTML element of the currently processed event (copy "all" of doSomething ").

Referring points

However, if you use inline event registration

What if I use in-row event registration?

<element onclick="doSomething()">

You do not copy the function! Instead, you refer to it, and the difference is crucial. The onclick property does not contain the actual function, but merely a function call:

There is no copy function here, But it points to it. What is the difference? This onclick attribute does not contain the actual function, but is just a function call.

doSomething();

So it says "Go to doSomething () and execute it." When we arrive at doSomething () the this keyword once again refers to the global window object and the function returns error messages.

The above means: "execute it in doSomething ". In doSomething (), if this keyword points to the global window object again, the function returns an error message.

------------ window --------------------------------------|                                          /            ||                                           |            ||                                          this          ||   ----------------                        |            ||   | HTML element | <-- this         -----------------  ||   ----------------      |           | doSomething() |  ||               |         |           -----------------  ||          -----------------------         /            ||          | go to doSomething() |          |            ||          | and execute it      | ---- reference to     ||          -----------------------       function        ||                                                        |----------------------------------------------------------
The difference is different?

If you want to use this for accessing the HTML element that is handling the event, you must make sure that the this keyword is actually written into the onclick property. only in that case does it refer to the HTML element the event handler is registered. so if you do

If you use this to access HTML elements to process events, you must be sure that it is actually written into the onclick attribute. Even if the event processing that points to the HTML element is registered. If you do this:

element.onclick = doSomething;alert(element.onclick)

You get

function doSomething(){this.style.color = '#cc0000';}

As you can see, the this keyword is present in the onclick method. Therefore it refers to the HTML element. But if you do

You can see that the this keyword is in The onclick method. It points to HTML elements. But if you do this:

<element onclick="doSomething()">alert(element.onclick)

You get

function onclick(){doSomething()}

This is merely a reference to function doSomething (). The this keyword is not present in the onclick method so it doesn't refer to the HTML element.

Here we only point to the function doSomething (). The this keyword is not in The onclick method. It does not point to HTML elements.

Examples-copying

This is written into the onclick method in the following cases:

In the following example, this is written to The onclick method:

element.onclick = doSomethingelement.addEventListener('click',doSomething,false)element.onclick = function () {this.style.color = '#cc0000';}<element onclick="this.style.color = '#cc0000';">
Examples-referring

In the following cases this refers to the window:

In the following example, this points to window:

element.onclick = function () {doSomething()}element.attachEvent('onclick',doSomething)<element onclick="doSomething()">

Note the presence of attachEvent (). the main drawback of the Microsoft event registration model is that attachEvent () creates a reference to the function and does not copy it. therefore it is sometimes impossible to know which HTML currently handles the event.

Note the above attachEvent. Its disadvantage is that the Microsoft Event registration model creates a point to this function and does not copy it. So sometimes it is impossible to figure out which HTML is currently processing the event.

Combination

When using inline event registration you can also send this to the function so that you can still use it:

When using in-row event registration, you can also send this to the function. So it can be used as follows:

<element onclick="doSomething(this)">function doSomething(obj) {// this is present in the event handler and is sent to the function// obj now refers to the HTML element, so we can doobj.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.