Understanding of this in JavaScript

Source: Internet
Author: User

The this in JavaScript is not as difficult as it is legendary, and it's not that messy.

Let us analyze, this is mainly related to its execution environment.

In general, this is placed in the function body or in the executable JS code (except for the function body).

As for the JS executable code in this, not much, so this article is less examples.

As for this in the function body, we just need to figure out who is calling the function body in this, do not know who this is?

Note: The function call in this article refers to the function being executed as a property method of an object, rather than simply executing in the scope of an object or calling

-------------------------------------------------------------------------------------------------------------

The This in the executable code (except for this contained in the function body)

1. This in the global Code

Alert (this)//window
View Code

2. This in the HTML event handler

<input type= "button" Name= "click" id= "click" value= "clicked" onclick= "Console.log (This)"/><!-- output: <input type= "button" Name= "click" id= "click" value= "clicked" onclick= "Console.log (This)" >-->
View Code

No.2 if the function body of this is not called by the object, this points to the window (the Default Call object is window). No matter where this function is, no matter how many layers are nested within the function body.

Example:

//First Floorfunctiontest1 () {Console.log ( This);//window    //Second Floor    functiontest2 () {Console.log ( This);//window        //Third Floor        functiontest3 () {Console.log ( This);//window            //Fourth Floor            functiontest4 () {Console.log ( This);//window} test4 ();    } test3 (); } test2 ();} Test1 ();
View Code

Examples of classification:

1. As a simple function call

function Test () {    console.log (this);  // window }test ();
View Code

2. As a constructor

function Person (name) {    this. Name = name;      this. Type = ' person ';      This function () {        alert ("eat");    };        Console.log (this//  Windowsvarnew person (" Wlh ");  // Person1
View Code

This point inside the function points to the newly constructed object, if not, to the window.

It's just the same as a simple function call, but with a name of a high-force lattice (constructor). (Understand the difference between a constructor and a normal function!) )

3. Object functions

var name = "Clever coder"; var person = {    ' foocoder 'function(sth) {    Console.log (this . Name + "says" + sth);}    } Person.hello ("Hello World");  // foocoder says hello world
View Code

This points to the person object, which is the current object.

The hello here is executed as a property method of person, so it points to the person

4. Internal function

var name = "Clever coder"; var person = {    "Foocoder",    function(sth) {        function  SayHello (sth) {            Console.log (this. Name + "says"+ sth);        };        SayHello (STH);    }} Person.hello ("Hello World"); // clever coder says hello world
View Code

In this intrinsic function, the SayHello function is executed only in the Person.hello function body.

However, it is not executed as a property method of the current object. So this inner function is still part of no object call, just executed. So it's inside this point to the window

It is clear that this point is pointing to the point of this, and then to the change of call (), apply (), bind ().

These three functions simply change this point of the current function and do not affect other places

-------------------------------------------------------------------------------------------------------------

Test to see if it's fully understood.

Practice One,

var age = +; function Person () {    var = +    ; this. Age =;   } Console.log (age);p Erson (), console.log (age);
View Code

Results:

var age = +; function Person () {    var = +    ; // If there is no explicit calling object (the default window call), then this is the equivalent of window, after executing person (), overriding the global variable    age this. Age =;   } Console.log (age);   //  + Person (); Console.log (age);   //  +
View Code

Exercise two:

var person = {age    :\function  person1 () {    var age = 20 ;     this. Age =;         function Person2 () {        var =N;         this. Age = All;    }    Person2 ();    } Console.log (person.age);p erson1.call (person);            Console.log (Person.age); Console.log (age);
View Code

Results:

varperson ={age:19}functionPerson1 () {varAge = 20;  This. Age = 21; functionPerson2 () {varAge = 22;  This. Age = 23;    } person2 (); }//The value of the age property of the person object is calledConsole.log (Person.age);// +//executes Person1 and uses call to point this to the person object in Person1. So this.age = Person.age =Person1.call (person); Console.log (Person.age); // +//this is the same as ' practice one ', if the calling object is not explicitly indicated, this points to the windowConsole.log (age);// at
View Code

This article is a way to re-understand this in JavaScript from another perspective.

This is the previous reprint of the blog: detailed JavaScript in this,

Understanding of this in JavaScript

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.