In-depth understanding of JavaScript's this keyword

Source: Internet
Author: User

In-depth understanding of JavaScript's this keyword
    • Author: laruence ()
    • This address: http://www.laruence.com/2009/09/08/1076.html
    • Reprint please indicate the source

JavaScript is a very flexible language, and the This keyword is flexible, but because of its flexibility, it is also doomed to its difficult to use.

When I used this, I would feel insecure, always worried that it would not know how to point to another place.

In fact, it's all because we don't know about it.

Just recently to Baidu College to do the "JavaScript advanced-scope/prototype chain" ppt, and swit1983 netizens also just mention this problem, simply put this part of the content of the independent summary, and share with you.

First, I'm going to throw a verdict: "In JavaScript, the This keyword always points to the owner of the function (method)."

Function

First, let's look at "functions":

    1. function introduce() {
    2. Alert("Hello, I am laruence\ r \ n");
    3. }

For this function, who does the This keyword point to?

As described in my previous article (JavaScript scope), defined in the global function, the owner of the function is the current page, that is, the Window object.

That's why I enclose the function in quotation marks. Because the function defined in the global is actually a method of the Window object.

Therefore, we can call directly by using the function name, or it can be called through the window. Method name, at this time, the This keyword in the method points to its owner: Window object.

If we look at the introduce property of window, we get:

  1. var name = "I am laruence";
  2. function introduce() {
  3. Alert(this. Name);
  4. }
  5. Alert(Window. Introduce);
  6. /**
  7. * Output:
  8. * Function introduce () {
  9. * Alert (this.name);
  10. * }
  11. */

Looking at the code above, you might think that since the global function is a method of the Window object, the global variable is the property of the Window object (as already stated in the Javasript scope), then the global variable can be accessed through the This keyword in the global function?

The answer is yes, if you call the introduce function, you will know that I am laruence.

Event handler function

Perhaps most of the confusion about this keyword comes from the use of functions (methods) in event processing.

    1. <input id="name" type="text" name= "name" value="laruence " />

For example, we now need to display the value of the name input box when we click on the "Name" input box. Then, you can write the following code:

    1. function showvalue() {
    2. Alert(this. Value);
    3. }
    4. Document. getElementById(' name '). onclick = Showvalue;

The code above is working fine, but why? Not to say that the this pointer of a function always points to the function owner? Not to say that the owner of a global variable is a Window object?

Hehe, if you can think of this problem, that means you are seriously looking at my article, otherwise, I suggest you start from the beginning, otherwise read, you still confused ~

Well, yes, for the above code, Showvalue is defined in the global object, so it seems that the problem only occurs when the OnClick event is bound.

We know that in JS everything is an object, and the function and method are all properties of the object, except that the function has an intrinsic property of the executable. So, for the above code, when binding the processor to the onclick, it is actually assigning a value to the OnClick property of the input box DOM object with ID name.

That is, we have showvalue Copy of the function to the OnClick property of the Name Input box object. If we look at the onclick at this point:

  1. function showvalue() {
  2. Alert(this. Value);
  3. }
  4. Document. getElementById(' name '). onclick = Showvalue;
  5. Alert(document. getElementById(' name '). onclick);
  6. /**
  7. * Output
  8. * Function Showvalue () {
  9. * Alert (This.value);
  10. * }
  11. */

Therefore, when the event is triggered, it will call the name input box's OnClick method, at this point, this keyword naturally points to the name input box.

However, the confusing thing is coming, such as the following:

    1. function showvalue() {
    2. Alert(this. Value);
    3. }
    4. <input id="name" type="text" name= "name" value="Laruence" onclick= "Showvalue ()"/>

will not work properly, why is this?

Well, because this time, it's not an assignment, it's a reference.

If we pay attention to the two kinds of onclick, you will find that, for the previous method, we are using:

    1. Dom. onclick = Showvalue; //No caller

And for the method just now:

    1. OnClick = "Showvalue ()" //has a caller

This can also reflect the difference between the two sides: for the former, is the assignment, and for the latter is a reference. If we look at the OnClick property of the input box at this time, we get:

    1. Alert(Dom. onclick);
    2. /**
    3. * Output:
    4. * Function onclick () {
    5. * Showvalue ();
    6. * }
    7. */

Do you see the difference? You know why, don't you?

Here, there is a very interesting example, you can try under IE:

    1. ="xxx" onerror="alert (1);} function hi () {alert (2); " />
Change the point of this

So, since we already know why, how can we get this point pointing to the place we want to refer to?

For the above event handler, there are several ways to write:

  1. Dom. onclick = showvalue();
  2. Dom. onclick = function() { alert(this. Value) ;}
  3. <input onclick="alert (this.value);" />//think about what we quoted just now , how to embed this sentence .
  4. Dom. AddEventListener(Dom, Showvalue, false); //ff only

For situations that are not event handlers, we can use apply, or call, to change the point of the This keyword.

Like what:

  1. var laruence = {
  2. Name : ' laruence ',
  3. Age :
  4. Position : ' Senior PHP Engineer ',
  5. Company : ' baidu.inc '
  6. };
  7. function introduce() {
  8. Alert(this. Name);
  9. }
  10. Introduce. Call(Laruence);

In-depth understanding of JavaScript's this keyword

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.