This usage of js

this is a keyword in JavaScript.

It represents an internal object automatically generated when the function runs, and can only be used inside the function. E.g:

function test(){
   this.x = 1;  
}

The value of this changes 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 discusses the usage of this in detail.

Case 1: Pure function call

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

Please look at this code of the project, its running result is 1.

function test(){

    this.x = 1;

    console.info(this.x);

}

test(); // 1

To prove that this is the global object, make the following changes to the code

var x = 1 ;

function test(){

    cosnole.info(this.x);

}

test(); // 1

The running result is still 1, let's change it again

   var x = 1 ;

  function test(){

    this.x = 0;

  }

  test();

  console.info (x); // 0

Case 2: Invocation as an object method

A function can also be called as a method of an object, in which case this refers to the superior object.

 function test(){

    alert(this.x);

  }

  var o = {};

  o.x = 1;

  o.m = test;

  man(); // 1

Case three is called as a constructor

The so-called constructor is to generate a new object (object) through this function. In this case, this refers to the new object.

  function test(){

    this.x = 1;

  }

  var o = new test();

  alert (ox); // 1

The result of running is 1. To show that this is not a 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

The running 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= {};

  o.x = 1;

  o.m = test;

  o.m.apply(); //0

 

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

If you change the last line of code to

o.m.apply(o); //1

The running result becomes 1, proving that this represents the object o at this time.

 

Guess you like

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