The This keyword in JavaScript is detailed

Source: Internet
Author: User
Tags setinterval

Original source: http://www.cnblogs.com/justany/archive/2012/11/01/the_keyword_this_in_javascript.html

Quiz

Take a look at the code below, what is 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, +);   9     }  ;  Nameobj.waitshowname ();

To solve this problem we need to understand 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 the most object-oriented programming languages, was this a special keyword that's used within methods to Refer to the object on which a method is being invoked.

--jquery Fundamentals (Chapter 2), by Rebecca Murphey

It is worth noting that the keyword is relevant in JavaScript and the execution Environment , not the declarative environment .

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

Let's give an example to illustrate the problem:

var someone = {    name: "Bob",    showname:function () {        alert (this.name);    }};  var other = {    name: "Tom",    showname:someone.showname}other.showname (); Tom

The This keyword is declared in Someone.showname, but is other.showname when it is run, so this is the current object of the Other.showname function, that is, other, so the last alert is other.name.

When there is no explicit current object

When there is no explicit execution of the current object, this points to the Global object window.

By default, this refers to the global object.

Why is it a global object, because a global variable in a non-browser case (for example: Nodejs) is not a Window object, but is called a "global variable" (the Universal object). However, since our article mainly discusses the front-end development knowledge, so the NODEJS is ignored by us.

For example, a global variable references a function on which we have:

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

You may also be able to understand that show is the method under the Window object, so when executing the current object, window. However, the local variable refers to a function that cannot be interpreted as such:

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 executed is the Global object window, which we can consider as a special case of the previous article.

So when the this.showname is running, this points to the window, so the Window.name is displayed at the end.

The global variables in the browser can be considered as variables under the Window object, such as global variable A, which can be referenced by WINDOW.A.

Changing the code to an anonymous function might better understand some of the following:

var name = "Bob";   var nameobj ={       Name: "Tom",       showname:function () {           alert (this.name);       },       waitshowname:function () {           !function (__callback) {            __callback ();        } (this.showname);       }   };    Nameobj.waitshowname (); Bob

When we call Nameobj.waitshowname, we run an anonymous function that passes Nameobj.showname as a callback function into this anonymous function, and then the anonymous function runs the callback function. Because the current object of the anonymous function is window, when you run the callback function in the anonymous function, this point of the callback function points to the 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 tips, we can get the answers we want:

var name = "Bob";  var nameobj ={      Name: "Tom",      showname:function () {          alert (this.name);      },      waitshowname:function () {        var = this;        SetTimeout (function () {            that.showname ();        }, +);}    };   Nameobj.waitshowname (); Tom

When we execute the Nameobj.waitshowname function, we assign the this to the variable that is (this is to avoid the anonymous function in the settimeout run, the This in the anonymous function points to the window), and then defer running the anonymous function, execute That.showname, NA Meobj.showname, so alert out the correct results Tom.

Eval

For the Eval function, it does not seem to specify the current object at execution time, but in fact its this does not point to the window, because the function executes at the scope of the current scope, which is equivalent to the code that is inside the row is filled in. 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 changes to the current object at the time the function executes, so this points to other objects. Because apply and call are more similar, we take apply as an example:

var name = "Window";    var someone = {    name: "Bob",    showname:function () {        alert (this.name);    }}; var other = {    name: "Tom"};    Someone.showName.apply ();    Windowsomeone.showName.apply (other);    Tom

Apply is used to change the current object when the function executes, and when there are no parameters, the current object is window and the current object is the parameter when there are parameters. So this example Bob successfully stole Tom's name.

New keyword

The this in the constructor after the new keyword points to the new object constructed with the constructor:

function Person (__name) {    this.name = __name;        This is a pointer to a new object constructed with this constructor, and 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 does the code below alert you of, and why?

var name = "Bob";  var nameobj ={      Name: "Tom",      showname:function () {          alert (this.name);      },      waitshowname:function () {        var = this;        SetTimeout ("That.showname ();", +);    };  Nameobj.waitshowname ();

2. What does the code below alert you of, and why?

var fun = new Function ("alert");

3. What are the differences between the following code in IE and other browsers, and how can I resolve this discrepancy?

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>

The This keyword in JavaScript is detailed

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.