SoFunction
Updated on 2025-03-01

Example analysis of this keyword usage example in JavaScript

This example summarizes the usage of this keyword in JavaScript. Share it for your reference, as follows:

Example 1:

function a(){
  var user = "yao";
  ();//undefined
  (this);//window
}
a();

Equivalent to:

function a(){
  var user = "yao";
  ();//undefined
  (this);//window
}
();

This points to window.

Example 2:

var o = {
  user:"yao",
  fn:function () {
    ();//yao
  }
}
();

This points to o.

Example 3:

var o = {
  user:"yao",
  fn:function () {
    ();//yao
  }
}
();

This points to o.

var o = {
  a:10,
  b:{
    a:12,
    fn:function () {
      ();//12
    }
  }
}
();

This points to b.

Example 4:

var o = {
  a:10,
  b:{
    a:12,
    fn:function () {
      ();//undefined
      (this);//window
    }
  }
};
var j = ;
j();

In summary:

This pointer is always the object that ultimately calls it.

When this encounters the return of the function:

Example 5:

function fn(){
   = "yao";
  return {};
}
var a = new fn;
();//undefined

Example 6:

function fn(){
   = "yao";
  return function(){};
}
var a = new fn;
();//undefined

Example 7:

function fn(){
   = "yao";
  return 1;
}
var a = new fn;
();//yao

Example 8:

function fn(){
   = "yao";
  return undefined;
}
var a = new fn;
();//yao

This points to the object returned by the function.

function fn(){
   = "yao";
  return null;
}
var a = new fn;
();//yao

Although: null is an object, this is still pointing to an instance of the function at this time.

PS:

In "use strict" mode, this default pointing is undefined, not window.

For more information about JavaScript, readers who are interested in reading this site's special topic:JavaScript object-oriented tutorial》、《Summary of common JavaScript functions techniques》、《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.