Usage of this. in js

this is a keyword in the Javascript language.

It represents an internal object automatically generated when the function runs and can only be used inside the function. For example,

  function test(){

    this.x = 1;

  }

will change the value of this depending on where the function is used. But there is a general principle that this refers to the object that called the function.

The following is divided into four situations, and the usage of this is discussed in detail.

Case 1: Pure function call

This is the most common usage of the function, which belongs to the global call, so this represents the global object Global.

Take a look at the following code, it runs as 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

is still 1. Change it again:

  var x = 1;

  function test(){

    this.x = 0;

  }

  test();

  alert(x); //0

Case 2: Calling as an object method A

function can also be called as a method of an object, and this refers to the superior object.

  function test(){

    alert(this.x);

  }

  var o = {};

  ox = 1;

  om = test;

  om(); // 1

case 3 is called as a constructor The

so-called constructor is to generate a new object. In this case, this refers to the new object.

  function test(){

    this.x = 1;

  }

  var o = new test();

  alert(ox); // 1

runs as 1. To show that this is not the global object at this point, I make some changes to the code:

  var x = 2;

  function test(){

    this.x = 1;

  }

  var o = new test();

  alert(x); //2

runs The result is 2, indicating that the value of the global variable x has not changed at all.

Case four apply call

apply() is a method of the function object. Its function is to change the calling object of the function. Its first parameter represents the changed object that calls the function. Therefore, this refers to this first parameter.

  var x = 0;

  function test(){

    alert(this.x);

  }

  var o={};

  ox = 1;

  om = test;

  omapply(); //0

When the parameter of apply() is empty, it is called by default global object. Therefore, the running result at this time is 0, which proves that this refers to the global object.

If the last line of code is modified to

  omapply(o); //1

, the result of operation becomes 1, which proves that this represents the object o at this time.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325973994&siteId=291194637