Home  >  Article  >  Web Front-end  >  What are the uses of this in javascript

What are the uses of this in javascript

coldplay.xixi
coldplay.xixiOriginal
2021-04-06 15:15:063699browse

Usage of this in JavaScript: 1. Use this to refer to the global object, the code is [alert(this.x)]; 2. Use this to refer to the superior object; 3. Use this to refer to the new object. object.

What are the uses of this in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Usage of this in javascript:

1. Use this to refer to the global object in general function methods

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

2. Call as an object method , this refers to the superior object

function test(){
  alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); // 1

3. As a constructor call, this refers to the object created by new

  function test(){
    this.x = 1;
  }
  var o = new test();
  alert(o.x); // 1
    //运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:
  var x = 2;
  function test(){
    this.x = 1;
  }
  var o = new test();
  alert(x); //2

4. Apply call, the apply method is to change the calling object of the function, this The first parameter of the method is the object that calls this function after the change, and this refers to the first parameter

  var x = 0;
  function test(){
    alert(this.x);
  }
  var o={};
  o.x = 1;
  o.m = test;
  o.m.apply(); //0
//apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。如果把最后一行代码修改为
  o.m.apply(o); //1

Related free learning recommendations: javascript Video tutorial

The above is the detailed content of What are the uses of this in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn