Home > Web Front-end > JS Tutorial > What are the usages of this in javascript?

What are the usages of this in javascript?

coldplay.xixi
Release: 2023-01-04 09:35:53
Original
2622 people have browsed it

Usage of this in JavaScript: 1. Use this to refer to the global object; 2. Use this to refer to the superior object; 3. Use this to refer to the new object; 4. Use this to refer to the first parameter. .

What are the usages 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 in general function methods to refer to the global object

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

2. When called 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
Copy after login

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
Copy after login

4. Apply call, the apply method is used to change the function The calling object. The first parameter of this method is the object that calls this function after the change. 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
Copy after login

Related free learning recommendations: javascript( video)

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

Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template