SoFunction
Updated on 2025-04-12

This pointer in detail

【This detailed explanation】

1. Whoever calls the function in the end, this points to.

① What this points to can only be an object forever! ! ! ! ! !

② Who this points to will never depend on where this is written! ! It depends on where the function is called.

③ The object pointed to by this is called the context of the function, also called the caller of the function

2. ※※※※※This pointing rule (closely related to the way function calls):

The situations pointed to by this depend on the way the function is called:

① Call directly through function name(): this points to window

② Called through object.function name(): this points to this object

③ The function is called as an element of the array and is called through the array subscript: this points to this array

④ The function is called as a callback function of the built-in function of the window: this points to window setInterval setTimeout, etc....

⑤ When the function is used as a constructor, when called with the new keyword: this points to the new object.

function func(){
   (this);
  }

① Call directly through function name (): this points to window

func(); this--->window

② Called through object.function name(): this points to this object

Narrow object

 var obj = {
 name:"obj",
 func1 :func
 };
 obj.func1(); this--->obj

Generalized object

 ("div").onclick = function(){
  = "red";
 }; this--->div

③ The function is called as an element of the array and is called through the array subscript: this points to this array

var arr = [func,1,2,3];
arr[0](); this--->arr

④ The function is called as a callback function of the built-in function of the window: this points to the window

setTimeout(func,1000);// this--->window
setInterval(func,1000);

⑤ When the function is called with the new keyword: this points to the new object

var obj = new func(); //this--->newNewobj

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.