SoFunction
Updated on 2025-02-28

Example analysis of this usage example in JavaScript

This article analyzes the usage of this in JavaScript. Share it for your reference, as follows:

1. "this" axiom

This keyword always points to the owner of the function (method);

function fn1(){
  this
};
fn1(); //this=>window
=fn1; //this=>oDiv
=function(){
  this //this=>oDiv
  fn1(); //this=>window
}
<div onclick="this.fn1();"></div> //This kind of writing between-line scripts is very rare now

This here points to the div, and this in fn1() points to the window

var it=
{
  info:["Tencent","Sohu","Sina","Baidu"],
  getinfo:function()
  {
    alert((","));
  }
};
();

Output: Tencent, Sohu, Sina, Baidu

2. "this" problem when function assignment to variables

var it=
{
  info:["Tencent","Sohu","Sina","Baidu"],
  getinfo:function()
  {
    alert((","));
  }
};
var data=;
data();

Output: Error, TypeError: is undefined

The code is equivalent to

var data=function(){
  alert((","));
};
data();

This here points to window, the data here is assigned. If it is var data=(); then it is called, and the result is Tencent, Sohu, Sina, and Baidu. If alert((",")); the result is still Tencent, Sohu, Sina, Baidu.

var info=["QQ","sohu","sina","baidu"]
var it=
{
  info:["Tencent","Sohu","Sina","Baidu"],
  getinfo:function()
  {
    alert((","));
  }
};
var data=;
data();

Output: QQ, sohu, sina, baidu

3. "this" problem when calling as an object method

function test()
{
  alert();
}
var o={};
=1;
=test;
();

Output: 1

4. "this" problem when calling as a constructor

var x=2;
function test()
{
  =1;
}
test();
alert(x);

Output: 1

var x=2;
function test()
{
  =1;
}
var o=new test();
alert();
alert(x);

Output: 1,2

5. "this" in closure points to problems

var it=
{
  info:["Tencent","Sohu","Sina","Baidu"],
  getinfo:function()
  {
  function abc(){
    alert((","));
  }
  abc();
  }
};
();

Output: Error, TypeError: is undefined

This in the closure cannot point to it

Solution

var it=
{
  info:["Tencent","Sohu","Sina","Baidu"],
  getinfo:function()
  {
  var _this=this;
  function abc(){
      alert(_this.(","));
  }
  abc();
  }
};
();

Advantages: No matter how the external function name (it) changes, it can point to info

For more information about JavaScript, please view the special topic of this site: "JavaScript object-oriented tutorial》、《Summary of json operation skills in JavaScript》、《Summary of JavaScript switching effects and techniques》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.