The analysis of this

Source: Internet
Author: User

This is a keyword in JS, when the function is run, an object is automatically generated and can only be used inside the function. This value changes as the letter is used, but always points to the object that called the function .

1. Purely function calls

function box () {    console.info (this),//window    this. x = "box";} Box (); Console.info (x); Box

The above description simply calls the function, which in the function represents window. I'll be writing two little chestnuts:

var x=1; function box () {    console.info (this. x);  // 1 }box ();

var x=1; function box () {    this. x =2;} Box (); Console.info (x); // 2

2. As a method of an object

When a function is called as a method of an object, this represents the object

The next three chestnuts are the most common method.

function test () {   console.info (this.x);} var o = {};o.x = 1;O.M=TEST;O.M ();//1,this stands for O

 

var o = {};o.x = 1;o.m =function () {    console.info (this.x);} O.M ();//1,this representative O

  

var o={    x:1,    m:function () {         console.info (this.x)       }}o.m ();//1 this represents O

  

3. Call as a constructor

That is, a new object is generated by the constructor, this represents the new object, which is very common.

function box () {    this. x = 1;  }  var New box (); Console.info (box1.x);//1 This represents Box1 object

4.apply Call

Apply is the method used to change the object that invokes the function, the first parameter represents the changed object, and the remaining parameter represents the passed-in parameter

var x = 0;function box () {    console.info (this.x);} var o={    x:1,    m:box}o.m ();//1o.m.apply ();//0o.m.apply (o);//1

Notice that when apply is passed, the delegate passes the window.

The analysis of this

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.