The This in JS

Source: Internet
Author: User

Http://www.jb51.net/article/41656.htm

Https://www.cnblogs.com/lisha-better/p/5684844.html

Https://www.ibm.com/developerworks/cn/web/1207_wangqf_jsthis/index.html

Http://www.cnblogs.com/justany/archive/2012/11/01/the_keyword_this_in_javascript.html

This is a keyword in the JavaScript language, which represents an internal object that is automatically generated when the function is run, can only be used inside the function, and in the following four cases, the usage of this is discussed in detail, and interested friends can understand that 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 the function. Like what
Copy CodeThe code is as follows:
function Test () {

this.x = 1;

}
The value of this will change as the function is used in different situations. But there is a general principle, that is, this refers to the object that called the function. In other words, in general, in JavaScript, this points to the function at execution timeThe current object. Execution Environment for functions

A function in JavaScript can be executed as a normal function or as a method of an object, which is the main reason for the richness of this meaning. When a function is executed, an execution environment (ExecutionContext) is created, and all the behavior of the function occurs in this execution environment, when the execution environment is built, JavaScript first creates a arguments variable that contains the arguments passed in when the function is called. Next, create the scope chain. Then initialize the variable, initialize the function's formal parameter list first, the value is the arguments corresponding value in the variable, and if arguments there is no corresponding value in the variable, the parameter is initialized undefined . If the function contains intrinsic functions, the intrinsic functions are initialized. If not, continue to initialize the local variables defined within the function, it is important to note that at this time the variables are initialized undefined , and their assignment is executed when the execution Environment (EXECUTIONCONTEXT) is successfully created, which is why we understand JavaScript The scope of the variables in is very important, given the length, we will not discuss this topic here. Finally, this assign a value to the variable, as described above, depending on how the function is called, assign to the this global object, the current object, and so on. The execution Environment (EXECUTIONCONTEXT) of the function is created successfully, the function begins to execute line by row, and the required variables are read from the previously built execution Environment (EXECUTIONCONTEXT).



The use of this is discussed in detail in four scenarios.

case One: purely function calls

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

Take a look at the code below, which results in a 1 operation.
Copy CodeThe code is as follows:
function Test () {

this.x = 1;

alert (this.x);

}

Test (); 1
To prove that this is a global object, I make some changes to the code:
Copy CodeThe code is as follows:
var x = 1;

function Test () {

alert (this.x);

}

Test (); 1
The result of the operation is still 1. Change it a little bit again:
Copy CodeThe code is as follows:
var x = 1;

function Test () {

this.x = 0;

}

Test ();

alert (x); 0
Scenario Two: Invocation as an object method

A function can also act as a method call to an object, at which point this is the ancestor object.
Copy CodeThe code is as follows:
function Test () {

alert (this.x);

}

var o = {};

o.x = 1;

O.M = test;

O.M (); 1
scenario Three is called as a constructor function

The so-called constructor is to generate a new object by this function (object). At this point, this is the new object.
Copy CodeThe code is as follows:
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:
Copy CodeThe code is as follows:
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.

scenario four apply call

Apply () is a method of a function object that changes the calling object of a function, and its first parameter represents the changed object that called the function. Therefore, this is the first parameter.
Copy CodeThe code is as follows:
var x = 0;

function Test () {

alert (this.x);

}

var o={};

o.x = 1;

O.M = test;

O.m.apply (); 0
The global object is called by default when the argument to apply () is empty. Therefore, the result of this operation is 0, which proves that this refers to the global object.

If the last line of code is modified to
Copy CodeThe code is as follows:
O.m.apply (o); 1
The result of the operation becomes 1, which proves that this represents the object OFunction.prototype.bind () method
    var name= "XL";    function person (name) {        this.name=name;        This.sayname=function () {            setTimeout (function () {                console.log ("My name is" +this.name);            },50)        }    }    var person=new person ("XL");    Person.sayname ()  //Output  "My name is XL";                       

So how can you output "my name is xl" it?

    var name= "XL";    function person (name) {        this.name=name;        This.sayname=function () {            setTimeout (function () {                console.log ("My name is" +this.name);            }. Bind (this),  //Note the bind () method used in this place, the settimeout of the anonymous function inside the binding is always pointing to the person object        }    }    var person=new Person ("XL");    Person.sayname (); Output "My name is XL";

Here setTimeout(function(){console.log(this.name)}.bind(this),50); , the anonymous function uses the bind(this) method to create a new function, and the new function, regardless of where it executes, this points to Person , and not window , so the final output is "My name is XL" instead of "My name is XL"

A few other areas to note:
setTimeout/setInterval/匿名函数执行, the this default point window对象 , unless you manually change the point of this. In JavaScript advanced programming, it is written that "the code for the timeout call ( setTimeout ) is executed in the global scope, so the value of this in the function is pointed to the Window object in non-strict mode, and to undefined in strict mode." This article is all in the case of non-strict mode.

  var name= "XL";    function person () {        this.name= "XL";        This.showname=function () {            console.log (this.name);        }        SetTimeout (this.showname,50);    }    var person=new person (); Output "XL"        //In the settimeout (this.showname,50) statement, the This.showname method is executed in a deferred manner    //this.showname method is the constructor person () The method defined inside. After 50ms, the This.showname method is executed, and this in This.showname points to the Window object. The "XL" will be output;

Modify the above code:

1   var name= "XL"; 2     function Person () {3         this.name= "XL"; 4         var that=this; 5         this.showname=function () {6             console.log (that.name); 7         } 8         setTimeout (this.showname,50) 9     }10     var person=new person (); /output "XL" one page///This is assigned to that in the person function, that is, let that save the person     object, so during settimeout (this.showname,50) execution, Console.log (That.name) Outputs the property "XL" of the person object

Anonymous functions:

1   var name= "XL"; 2     var person={3         Name: "XL", 4         showname:function () {5             console.log (this.name); 6         } 7         sayname:function () {8             (function (callback) {9                 callback ();)             (this.showname)         }12     }13     person.sayname ();  Output XL14     var name= "XL";     var person={16         name: "XL", +         showname:function () {             Console.log (this.name),         }20         sayname:function () {+             var that=this;22             (function (callback) {23                 callback ();             (that.showname)         }26     }27     person.sayname ();  Output  "XL" The     execution of the anonymous function is also by default this is pointing to the window unless you manually change the bound object of this
eval function

When the function executes, this is bound to the current scope of the object. The Eval method in JavaScript can convert a string to JavaScript code, where does this point when using the Eval method? The answer is simple, see who is calling the Eval method, and this in the caller's execution Environment (ExecutionContext) is inherited by the Eval method.

    var name= "XL";    var person={        name: "XL",        showname:function () {            eval ("Console.log (THIS.name)");        }    }        Person.showname ();  Output  "XL"        var A=person.showname;    A ();  Output  "XL"

Arrow functions

es6thisit points to the anchor, always points to the outer object, because the arrow function is not this , so it cannot be instantiated by itself new , nor can it use call, apply, bind the method to change this the point

   function Timer () {        this.seconds = 0;        SetInterval (() = This.seconds + +, +);    }         var timer = new timer ();        SetTimeout (() = Console.log (timer.seconds), 3100);        3   //within the setinterval () callback function inside the constructor, this always points to the instantiated object and gets the seconds property of the instantiated object, and the value of this property is incremented by 1 per 1s. Otherwise, after the execution of the settimeout () function after 3s, the output is 0.

The This in JS

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.