JavaScript's This keyword usage

Source: Internet
Author: User

This is a keyword in the JavaScript language.

It represents an internal object that is automatically generated when the function is run, and can only be used inside a function. Like what

function Test () {

this.x = 1;

}
The value of this will change as the function is used differently. But there is a general principle, and that is this refers to the object that invokes the function.

Here are four different scenarios for a detailed discussion of this usage.

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.

function Test () {

this.x = 1;

alert (this.x);

}

Test (); 1
To prove that this is the global object, I make some changes to the code:

var x = 1;

function Test () {

alert (this.x);

}

Test (); 1
The results of the operation are still 1. Change again:

var x = 1;

function Test () {

this.x = 0;

}

Test ();

alert (x); 0
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.

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.

function Test () {

this.x = 1;

}

var o = new Test ();

alert (o.x); 1
The run result is 1. To show that this is not a global object, I make some changes to the code:

var x = 2;

function Test () {

this.x = 1;

}

var o = new Test ();

alert (x); 2
The run result is 2, indicating that the value of global variable x does not change at all.

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.

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 run turns into 1, proving that this is the object o.

Add:

Take a look at the code below, what's the last alert?


1 var name = "Bob";
2 var nameobj ={
3 Name: "Tom",
4 Showname:function () {
5 alert (this.name);
6},
7 waitshowname:function () {
8 settimeout (this.showname, 1000);
9}
10};
11
Nameobj.waitshowname (); To solve this problem we need to know the use of the This keyword for JavaScript.

Where does this point?

In general, in JavaScript, this points to the current object when the function executes.

In JavaScript, as in most object-oriented programming languages, this is a special keyword the is used within to Refer to the "object on which a" is being invoked.

--jquery Fundamentals (Chapter 2), by Rebecca Murphey
It is worth noting that this keyword is relevant in JavaScript and in the execution environment, not in declaring the environment.

The This keyword are relative to the execution context and not the declaration context.

Let us give an example to illustrate this problem:


var someone = {
Name: "Bob",
Showname:function () {
alert (this.name);
}
};

var other = {
Name: "Tom",
ShowName:someone.showName
}

Other.showname (); The Tomthis keyword is declared in Someone.showname, but the runtime is other.showname, so this points to the current object of the Other.showname function, that is, the other, so the last alert comes out of other.name 。

When there is no explicit current object

This points to the Global object window when there is no explicit execution of the current object.

By default, this is refers to the global object.

Why is the global object, because the global variable is not a Window object (for example: Nodejs) in a non-browser case (e.g., "global"). However, because our article mainly discusses the front-end development knowledge, so Nodejs is we ignore.
For example, for a function referenced by a global variable, we have:


var name = "Tom";

var Bob = {
Name: "Bob",
Show:function () {
alert (this.name);
}
}

var show = Bob.show;
Show (); Tom, you might as well understand that show is a method under the Window object, so when the current object is executed, window. However, the functions referenced by local variables do not explain this:


var name = "Window";

var Bob = {
Name: "Bob",
Showname:function () {
alert (this.name);
}
};

var Tom = {
Name: "Tom",
Showname:function () {
var fun = Bob.showname;
Fun ();
}
};

Tom.showname (); Window

SetTimeout, setinterval, and anonymous functions

The answer to the question at the beginning of the article is Bob.

The current object in the browser when settimeout, setinterval, and anonymous functions are executing is the Global object window, which we can consider to be a special case of the previous one.

So at the time of running This.showname, this points to window, so it finally shows Window.name.

A global variable in a browser can be treated as a variable under a Window object, such as global variable A, which can be referenced by WINDOW.A.
We might be able to better understand some of the code by changing it to an anonymous function:


var name = "Bob";
var nameobj ={
Name: "Tom",
Showname:function () {
alert (this.name);
},
Waitshowname:function () {
function (__callback) {
__callback ();
} (This.showname);
}
};

Nameobj.waitshowname (); When Bob called Nameobj.waitshowname, we ran an anonymous function that passed the Nameobj.showname function as a callback function, and then ran the callback function when the anonymous function ran. Because the current object of the anonymous function is window, when the callback function is run in the anonymous function, this point to window, so alert comes out window.name.

It seems that settimeout can be seen as a deferred execution:

function (__callback) {
__callback ();
}setinterval is also so analogous.

But what if the answer we really want is Tom? With some skill, we can get the answers we want:


var name = "Bob";
var nameobj ={
Name: "Tom",
Showname:function () {
alert (this.name);
},
Waitshowname:function () {
var that = this;
settimeout (function () {
That.showname ();
}, 1000);
}
};

Nameobj.waitshowname (); When Tom executes the Nameobj.waitshowname function, we first assign this to the variable that (in order to avoid the anonymous function in settimeout, this point to window), and then delay the run of anonymous functions, execute the That.shownam E, IE nameobj.showname, so alert out the correct result of Tom.

Eval

For the Eval function, it does not seem to specify the current object at its execution time, but in fact it does not point to window because the function executes at the current scope, which is equivalent to the code inside the line. The following example illustrates the problem:


var name = "Window";

var Bob = {
Name: "Bob",
Showname:function () {
Eval ("Alert (this.name)");
}
};

Bob.showname (); Bob

Apply and call

Apply and call can force the current object to be changed when the function executes, letting this point to another object. Because apply and call are more similar, we use apply as an example:


var name = "Window";

var someone = {
Name: "Bob",
Showname:function () {
alert (this.name);
}
};

var other = {
Name: "Tom"
};

Someone.showName.apply (); Window
Someone.showName.apply (other); Tomapply is used to change the current object when the function executes, when there is no argument, the current object is window, and the current object is the parameter when there is a parameter. So this example Bob succeeded in stealing Tom's name.

New keyword

This in the constructor after the new keyword points to a new object constructed with the constructor:


function Person (__name) {
THIS.name = __name; This is a new object constructed with this constructor, this example is the Bob Object
}
Person.prototype.show = function () {
alert (this.name);
}

var bob = new Person ("Bob");
Bob.show (); Bob

Study Questions

1. What is the following code alert, and why?


var name = "Bob";
var nameobj ={
Name: "Tom",
Showname:function () {
alert (this.name);
},
Waitshowname:function () {
var that = this;
SetTimeout ("That.showname ();", 1000);
}
};

Nameobj.waitshowname (); 2. Will the following code alert what, Why?

var fun = new Function ("alert (This)");
Fun (); 3. What is the difference between the following code running on IE and other browsers, and what can be used to solve the discrepancy problem?

Ie:


<button id = "box" name = "box" >click me!</button>

<script>
var name = "Window";

function ShowName () {
alert (this.name);
}

document.getElementById ("box"). Attachevent ("onclick", showname);
</script>others:


<button id = "box" name = "box" >click me!</button>

<script>
var name = "Window";

function ShowName () {
alert (this.name);
}

document.getElementById ("box"). AddEventListener ("Click", ShowName, false);
</script>

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.