JavaScript this keyword usage introduction

Source: Internet
Author: User

I used this when I would feel uneasy, always worried that it does not know how to point to another place.

In fact, this is because, we do not understand it.

Just recently to Baidu Institute to do "JavaScript advanced-scope/prototype chain" ppt, and swit1983 Netizen also just mention this problem, simply put this part of the content independently summed up, and share with you.

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

Function

First, let's look at "functions":

The code is as follows Copy Code

function introduce () {

Alert ("Hello, I am Laruencern");

}< li>

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

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

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

So, we can call directly using the function name, or by window. Method name, at which point the This keyword in the method points to its owner: Window object.

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

The code is as follows Copy Code

var name = "I am laruence";

function introduce () {

alert (this.name);

}

alert (window.introduce);

/**

* Output:

* Function introduce () {

* Alert (this.name);

* }

*/< li>


Looking at the code above, you might think that since the global function is the method of the Window object, the global variable is the property of the Window object (already described 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 the most reason for the confusion of this keyword is that the function (method) is used in event handling.

The code is as follows Copy Code

<input id= "name" type= "text" name= "name" value= "Laruence"/>< li>

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:

The code is as follows Copy Code

function Showvalue () {

alert (this.value);

}

document.getElementById (' name '). onclick = showvalue;< li>


The code above, running normally, but why? Not to say that the this pointer of a function always points to the function owner? Is it not that the owner of the global variable is a Window object?

Oh, if you can think of this problem, it means that you are seriously looking at my article, otherwise, I suggest you look 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 can only happen when the OnClick event is bound.

We know that in JS everything is an object, functions and methods are also objects of the property, but the function has executable internal properties. So, for the above code, the OnClick property of the input box DOM object with ID name is assigned to the onclick binding processor.

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

The code is as follows Copy Code

function Showvalue () {

alert (this.value);

}

document.getElementById (' name '). onclick = Showvalue;

Alert (document.getElementById (' name '). onclick);

/**

* Output

* Function Showvalue () {

* Alert (This.value);

* }

*/< li>


So, when the event is triggered, the OnClick method of the name input box is invoked, and this keyword naturally points to the name input box.

However, the confusing things come, such as the following wording:

The code is as follows Copy Code

function Showvalue () {

alert (this.value);

}

<input id= "name" type= "text" name= "name" value= "Laruence" onclick= "Showvalue ()"/><

is not functioning properly, what is this?

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

If we pay attention to both types of onclick, you will find that for the previous method, we used the following:

Dom.onclick = Showvalue; No caller < li>


And for the method just now:

onclick = "Showvalue ()"//With caller < li>


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 view the OnClick property of the input box at this time, we get:

The code is as follows Copy Code

alert (Dom.onclick);

/**

* Output:

* Function onclick () {

* Showvalue ();

* }

*/< li>


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

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

The code is as follows Copy Code

< li>

Change the point of this

So, since we already know why, how can we let this point to where we want to refer?

For the above event-handling functions, there are several ways to write:

The code is as follows Copy Code

Dom.onclick = Showvalue ();

Dom.onclick = function () {alert (this.value);}

<input onclick= "alert (this.value);"/>//think about how our quote was embedded in this sentence.

Dom.addeventlistener (DOM, Showvalue, false); FF only< li>


For situations that are not event-handling functions, we can use apply, or call, to change the point of this keyword.

Like what:

The code is as follows Copy Code

var laruence = {

Name: ' Laruence ',

Age:26,

Position: ' Senior PHP Engineer ',

Company: ' Baidu.inc '

};

function introduce () {

alert (this.name);

}

Introduce.call (laruence);< li>


Use the This keyword in the event handler function in a DOM way:

The code is as follows Copy Code

<div id= "Elmtdiv" >division element</div>
<script language= "JavaScript" >
var div = document.getElementById (' Elmtdiv ');
Div.attachevent (' onclick ', EventHandler);

function EventHandler ()
{
Use this here
}
</script>

The This keyword in the EventHandler () method indicates that the object is the window object for IE. This is because EventHandler is just an ordinary function, and for attachevent, the script engine has no relationship to its invocation and the Div object itself. You can also look at the caller property of EventHandler, which is equal to NULL. If we want to get a Div object reference in this method, we should use: This.event.srcElement.

Use the This keyword in the event handler function in DHTML mode:

The code is as follows Copy Code

<div id= "Elmtdiv" >division element</div>
<script language= "JavaScript" >
var div = document.getElementById (' Elmtdiv ');
Div.onclick = function ()
{
Use this here
};
</script>

Here the This keyword indicates a DIV element object instance that uses DHTML in the script to assign a EventHandler method directly to the Div.onclick and adds a member method to the Div object instance. The difference between this and the first approach is that the first approach is to use HTML, which is DHTML, and the script resolution engine no longer generates anonymous methods.

Use this keyword in class definitions:

The code is as follows Copy Code

function Jsclass ()
{
var myname = ' Jsclass ';
This.m_name = ' Jsclass ';
}

JSClass.prototype.ToString = function ()
{
Alert (myname + ', ' + this.m_name);
};

var JC = new Jsclass ();
Jc. ToString ();

Here you will probably understand how this is used, as well as some of the differences between the variable declaration and the JS VAR declaration variable.

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.