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

What are the uses of this in javascript

coldplay.xixi
Release: 2023-01-04 09:34:31
Original
3909 people have browsed it

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

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

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!

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