SoFunction
Updated on 2025-04-14

An article explains in detail this (ordinary functions, arrow functions, and function application) in JavaScript

Preface

This object: Every time the parser calls a function, it will pass an implicit parameter to the function. This parameter is this. This pointes to an object. We call this object. This object. This object is called the context object of function execution. Depending on the method of function calling, this will point to different objects.

1. This is the directive problem based on the following aspects

  • This in the global environment
  • This in the function
  • This in object method
  • This in the constructor
  • This in event handler function
  • This in the arrow function

1. This in the global environment

In a global environment (not inside any function or object), this points to a global object (in the browser environment iswindow, in theglobal

(this === window); // Output true in the browser

2. This in the function

When a function is called directly, this points toGlobal Object(window), pointing toundefined

JS Strict Pattern: JavaScript has some vague features in syntax and behavior, which may lead to some unobservable errors. In order to improve the quality and maintainability of the code, js has introduced a strict pattern, enforcing stricter syntax and behavior by enabling some additional rules. Potential issues in the code in strict mode will be caught and errors are thrown, helping to detect and fix potential bugs in advance.

function regularFunction() {
  (this);
}

regularFunction(); // Point to window in non-strict mode, undefined in strict mode
// Demonstrate the situation in strict mode(function () {
  "use strict";
  regularFunction();
})();

3. This in object method

When a function is called as an object, this points to the object that calls the method

var person = {
  name: "John",
  sayName: function () {
    ();
  }
};

(); // Output "John", here this points to the person object

4. This in the constructor

When calling a function using the new keyword (instance), the function is treated as a constructor (class), and this will point to the newly created object instance

function Person(name) {
   = name;
   = function () {
    ("Hello, I'm " + );
  };
}

var john = new Person("John");
(); // Output "Hello, I'm John", here this points to the john instance

How to execute the process of creating an object by constructor:

  • Call a constructor and it will immediately create an object
  • Set the newly created object to this in the function,This can be used in the constructor to refer to the newly created object
  • Execute the code in the function line by line
  • Return the newly created object as the return value

In the constructor, both the creation and return objects are hidden for us. Objects created using the same constructor are called a class of objects, and a constructor is also called a class. We will call an object created through a constructor an instance of the class.

5. This in event handling function

In DOM event handlers, this usually points to the element that triggers the event.

<button >Click me</button>

<script>
  var button = ("myButton");
   = function () {
    (this); // When clicking a button, this here points to the button element    				  //Print: <button >Click me</button>  };
&lt;/script&gt;

7. This in the arrow function

The arrow function does not have this of its own, its this inherits from this of the outer scope.

// Normal functionsfunction outerFunction() {
   = "Outer";
  var innerFunction = function () {
    ();
  };
  innerFunction();
}

// Arrow functionfunction outerFunctionWithArrow() {
   = "Outer with Arrow";
  var innerFunction = () =&gt; {
    ();
  };
  innerFunction();
}

new outerFunction(); // Output undefined, because this in innerFunction points to the global object, the global object does not have a name attributenew outerFunctionWithArrow(); // Output "Outer with Arrow", this of the arrow function inherits from this of outerFunctionWithArrow

2. Change the method of this pointing

Since this of the arrow function comes from inheritance, the arrow function cannot change this pointing using the following three methods

1. Call() method

  • callThe method is attached to the function call and can ignore this pointer of the function itself.
  • Syntax: function name.call (the pointer to change, parameter 1 to be passed to the function, parameter 2 to be passed to the function, ...)
  • When using the call method:
    1. The function will be executed immediately
    2. The first parameter is the pointer of this inside the function you want to change
    3. The second parameter starts, passing parameters to the function in turn
var obj = { name: 'Jack' }
function fn(a, b) {
  (this)
  (a)
  (b)
}
fn(1, 2)
(obj, 1, 2)
  • fn(1,2)When  , this inside the function points to the window (the function is called directly)
  • (obj, 1, 2)When this function points to the object obj

2. Apply() method

  • applyThe method is attached to the function call and can ignore this pointer of the function itself.
  • Syntax: function name.apply (this pointer to change, [parameter 1 to be passed to the function, parameter 2 to be passed to the function, ...])
  • When using the call method:
    1. The function will be executed immediately
    2. The first parameter is the pointer of this inside the function you want to change
    3. The second parameter is oneArray, each item in the array is the parameters passed to the function in turn (the main difference between the call method)
var obj = { name: 'Jack' }
function fn(a, b) {
  (this)
  (a)
  (b)
}
fn(1, 2)
(obj, [1, 2])
  • fn(1,2)When  , this inside the function points to the window (the function is called directly)
  • (obj, 1, 2)When this function points to the object obj

3. bind() method

  • bindThe method is attached to the function call and can ignore this pointer of the function itself.
  • There is some difference between call / apply, which is that the function will not be executed immediately, but returns a function that has changed its pointer to
  • Syntax: var newFn = function name.bind (this pointer to be changed); newFn (pass parameter)
var obj = { name: 'Jack' }
function fn(a, b) {
  (this)
  (a)
  (b)
}
fn(1, 2)
var newFn = (obj)
newFn(1, 2)
  • When the bind is called, the function fn is not executed, but a new function is returned.
  • This new function is a function that changes this points to the future fn function.
  • fn(1, 2)When this points to window
  • newFn(1, 2)When  is executed a function that is exactly the same as fn, except that the pointer in this is changed to obj

3. This pointing in the callback function

Here we add this pointing point (also a knowledge point that is easy to confuse) in the use of callback function.

1. Object method as callback function

If the callback function is an object's method and is passed in as an object method, then this will usually point to that object.

var myObject = {
  value: 10,
  callbackFunction: function () {
    ();
  }
};
[1,2,3].forEach(() =&gt; {
  ()
});        //Output three 10

In this example, forEach is an array method, passed as a callback function to forEach. When forEach calls this callback function, this still points to myObject, because this function is essentially a method of myObject.

2. Arrow function as callback function

The arrow function does not have its own this, it inherits this from the outer scope (according to the lexical scope rules).

function outerFunction() {
   = "Outer";
  var array = [1, 2, 3];
  (() =&gt; {
    ();  //Print Outer three times  });
}
new outerFunction();

Based on the above two examples, here we introduce itNormal functionsandArrow functionSome differences when determining this pointing:

1. Ordinary functions

Ordinary functions determine the scope of the function when defining a function, but do not specify the point of this in the function. The pointing of this in ordinary functions is determined when the function is called (pointing to the caller or global object)

2. Arrow function

Since the arrow function itself does not generate this, this inherits from the outer scope. When defining, the arrow function not only determines the scope, but also captures this of the outer scope as its own this. This of the arrow function is determined when defining. When the subsequent function calls, no matter who called the arrow function, its pointing will not change.

The above example is an example:

The arrow function is defined inside the outerFunction function, note that it is not defined inside the forEach method. For details, you can understand the steps of passing the function parameters. Here, the arrow function is first defined inside the outerFunction function, and then passed as a parameter to the forEach method. The arrow function inherits this from the outerFunction function and does not change afterwards when called by the forEach method.

3. Common situations in which callback functions point to global objects

When a normal function is a callback function, and this normal function is called by a global function (such as setTimeout, setInterval) or a function called independently in the global scope (not called through an object), in non-strict mode, this usually points to the global object.

//Called by a global functionsetTimeout(function () {
  (this); 
}, 1000);
//Call independently in the global scope  function outer(){
    inner()
  }
  function inner(){
    (this);
  }
  outer()

4. Summary and common error examples

This points to:1. Ordinary functions: Whoever calls the function, this points to whom, and without the caller, it points to the global object Window
2. Arrow function: The arrow function will not create this, its this inherits from this in the upper scope.

1. Case 1

//Use this incorrectly in the callback functionvar person = {
  name: "Eve",
  greetLater: function () {
    setTimeout(function () {
      (); // The function here is a normal function, as the parameter of setTimeout this points to the global object    }, 1000);
  }
};

();

The function here is a normal function, called by a global function, whose this points to the global object Window.

To output Eve, just change the normal function here to an arrow function.

var person = {
  name: "Eve",
  greetLater: function () {
    setTimeout( ()=&gt; {
      (); // Output Eve    }, 1000);
  }
};

();

2. Case 2

//Confuses this pointing in nested functionsvar outer = {
  name: "Outer Object",
  innerFunction: function () {
    var inner = {
      name: "Inner Object",
      nestedFunction: function () {
        (); // Here this points to inner, not outer      }
    };
    ();
  }
};

();

nestedFunction is a method called as an inner object, and this points to the inner object (according to the rules pointed to by the ordinary function this, when a function as an object's method is called, this points to the object that calls the function.)

4.2.1. Methods of using outer scope this

To access the name property of the outer object, you can use the following two methods:

1. Save the reference to this outer layer

var outer = {
  name: "Outer Object",
  innerFunction: function () {
    var self = this;
    var inner = {
      name: "Inner Object",
      nestedFunction: function () {
        (); // You can now access the name property of the outer and output "Outer Object"      }
    };
    ();
  }
};

();

At the beginning of the method, save this to a variable (usually named self or that, etc.), and then use this saved variable in the inner object to access the properties of the outer object.

2. Use arrow function

var outer = {
  name: "Outer Object",
  innerFunction: function () {
    var inner = {
      name: "Inner Object",
      nestedFunction: () =&gt; {
        (); // Output "Outer Object"      }
    };
    ();
  }
};

();

Change nestedFunction to an arrow function, because the arrow function will inherit this from the outer scope. Here the outer scope is (), which this points to the outer object, so this in the arrow function can also point to the outer object.

Summarize

This is the article about this (ordinary functions, arrow functions, and function application) in JavaScript. For more related contents of this ordinary functions, arrow functions, and callback functions in JS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!