This keyword is used in JavaScript

Source: Internet
Author: User

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

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");

}

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);

* }

*/


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"/>


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;


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);

* }

*/


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 invoke character

And for the method just now:

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 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 ();

* }

*/


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

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


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);

Here are a few more things we can do.


Case one: pure function call

This is the most common use of a function, which is a global call, so this represents the globally object.

Take a look at the code below and it runs 1.

JavaScript code

The code is as follows Copy Code
function Test () {
this.x = 1;
alert (this.x);
}
Test (); 1

Case two: Call as an object method

A function can also be invoked as a method of an object, at which point this is the ancestor object.

JavaScript code

The code is as follows Copy Code
function Test () {
alert (this.x);
}
var o = {};
o.x = 1;
O.M = test;
O.M (); 1

Case three is called as a constructor function

The so-called constructor, is to generate a new object by using this function. At this point, this is the new object.

The code is as follows Copy Code

JavaScript code
function Test () {
this.x = 1;
}
var o = new Test ();
alert (o.x); 1

Condition four Apply Call

Apply () is a method of a function object that changes the calling object of the function, and its first argument represents the object that called the function after the change. So, this is the first argument.

JavaScript code

The code is as follows Copy Code
var x = 0;
function Test () {
alert (this.x);
}
var o={};
o.x = 1;
O.M = test;
O.m.apply (); 0

When the parameter to apply () is empty, the global object is called by default. Thus, the result of this operation is 0, proving that this refers to a global object.

If the last line of code is modified to: O.m.apply (o); 1

The operation turned out to be 1, proving that this is the object o

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.