About the This keyword in JavaScript (translation + self-understanding) _javascript Tips

Source: Internet
Author: User
Here are about 70% of the content from http://www.quirksmode.org/js/this.html, and the other 30% is my own understanding of it and feelings. Hope to help people who need it ...

First, look at a very typical topic about this keyword:
Copy Code code as follows:

var name = ' The '
var obj = {
Name: ' Ru ',
Getname:function () {
return function () {
return this.name;
};
}
}
Alert (Obj.getname () ());

This is not suspense, the result of the implementation is:
Slightly change the code:
Copy Code code as follows:

var name = ' The '
var obj = {
Name: ' Ru ',
Getname:function () {
var that = this;
return function () {
return that.name;
};
}
}
Alert (Obj.getname () ());

The execution result is: RU
The execution result is: RU

The reasons for this result are discussed in detail below.
"Owner of the function"
To explain this, first say the concept. In JavaScript, this always points to the owner of the function we are currently executing. More specifically, it points to the object that takes this function as a method.
This sentence how to understand, we can look at the following example:
Copy Code code as follows:

/*--test1--* *
function Test1 () {
This.title = ' me ';
Alert (window[' title ')];
Alert (this = = window); True
}
Test1 ();


Execution result is: me, true
In the example above, this is pointing to the Window object. and write the Title property of window This object as ' me ' because test1 is a top-level function, so its owner is a window object, or it's a method of a Window object. This should not be difficult to understand. such as the above call Test1 (), can also be written as Window.test1 (), so clear.

Next, we build a div and assign the Test1 as a method to the OnClick property of the Div:
Copy Code code as follows:

<div id= "O" style= "width:50px;height:50px;border:4px solid #333" >me!</div>
<script type= "Text/javascript" >
/*--test1--* *
function Test1 () {
This.title = ' me ';
Alert (window[' title ')];
Alert (this = = window);
}
var o = document.getElementById (' o ');
O.onclick = test1;
</script>

Click on the div result: undefined, false; At the same time we use Firebug to see that the attribute value of ' me ' is actually assigned to this htmlobject with ID ' o '

Obviously, this point points to this div, that is, the owner of the Test1 () becomes the Div htmlobject, or it becomes the div's OnClick method to invoke. This situation should still be easy to understand.
Next we change the code, and then change a place:
Copy Code code as follows:

O.onclick = Test1 (); Note: Parentheses are added here

After changing the last sentence of the above code to this, the result of clicking the div is: me, true
became the same as the first case, this points to window. Some people will wonder, feel no difference, in fact, there is a difference. This involves the question of the copy and refer of the function.

"Copy of Function"
If you pass
Copy Code code as follows:

O.onclick = test1;

This way, in fact, is to put test1 () This function copy to the object O's OnClick property. So the owner of the Test1 became the object of O.
If you pass
Copy Code code as follows:

O.onclick = Test1 ();

In this way, it essentially means that when the handle of the Click event is obtained, it is directed to perform the Test1 () function. Note that the instructions are directed to execute rather than assigned to it. The owner of Test1 () has not changed, or window.

"Refer of Functions"
Ditto, we use the inline way to write the call to the HTML to invoke the words, or the refer way
Copy Code code as follows:

<div id= "O" style= "width:50px;height:50px;border:4px solid #333" onclick= "test1 ()" >me!</div>

Click the div execution result or show this to point to window.
"Examples of function copy"
Copy Code code as follows:

Element.onclick = dosomething
Element.addeventlistener (' click ', Dosomething,false)
Element.onclick = function () {This.style.color = ' #cc0000 ';}
<element onclick= "This.style.color = ' #cc0000 ';" >

These ways make this point the object of the current call.
"Examples of function refer"
Copy Code code as follows:

Element.onclick = function () {dosomething ()}
Element.attachevent (' onclick ', dosomething)
<element onclick= "dosomething ()" >

These methods do not change the owner of the function, it should be noted that AddEventListener and attachevent are inconsistent, because attachevent is actually built a reference to DoSomething, Instead of copy this function.

"By the way of call."
Just now we said that writing <element onclick= "test ()" > could not make the owner of Test () a <element>
Copy Code code as follows:

<element onclick= "Test (This)" >
Function (o) {
O.title = ' me ';
}

This explicit invocation is possible. Alternatively, using the object of call or apply to impersonate the inheritance method can also
Copy Code code as follows:

<element onclick= "Test.call (This)" >
function Test () {
This.title = ' me ';
}

This is also the most typical way to impersonate an object.

"Free variable Problem"
Written so long, we still go back to the beginning of the question:
Copy Code code as follows:

var name = ' The '
var obj = {
Name: ' Ru ',
Getname:function () {
return function () {
return this.name;
};
}
}
Alert (Obj.getname () ());

Why is the result of this approach? Focus on
Copy Code code as follows:

return function () {
return this.name;
};

In contrast to the example of the function refer written above, it is not difficult to find that the return of this anonymous function is called with the onclick = function () {dosomething ()}. So this way does not change the owner of this function, which is a nested function, but its declaration is top-level. Where this is pointing to window.
The second way is to force this to be assigned to that in GetName (), which means that that.name is actually the same as the THIS.name in GetName (). In the context of GetName, its owner is the object of obj, so this will point to obj, so this.name = = Obj.name;
I don't know if I'm going to take you around this whole circle.

It can be summed up in this way: in the context of the function where this is, if the function is not invoked as a "method", then this one points to the Window object or points to the owner of the function.
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.