Home > Web Front-end > JS Tutorial > body text

How do I access the correct 'this' in the callback?

WBOY
Release: 2023-08-24 09:53:09
forward
994 people have browsed it

How do I access the correct this in the callback?

In this tutorial we will see how to access the correct "this" in the callback.

"This" keyword

Every function contains a keyword called this, also known as "context", whose value is determined by how the function is called, not by how, when, or where the function is defined. Unlike other variables, it is not affected by lexical scope. Compared to other languages, JavaScript behaves slightly differently when using the "this" keyword of a function. There are some further changes between strict and non-strict mode.

The way the function is most commonly called determines the value of "this" (runtime binding). It may change each time the function is called, and cannot be changed by assignment at execution time. Number of times the function is called, the bind() method can set this value because arrow functions do not provide their own "this" binding (it retains the "this" value of the enclosing lexical context).

What is a callback?

A function that receives parameters from another function is called a callback and is usually used later in an external function. Higher-order function is a term used to describe external functions that accept callbacks.

Callbacks have their own set of methods and properties because functions are objects in JavaScript. The "this" attribute assigned to a callback when executed within a higher-order function depends entirely on how the callback is made, not where, how, or when it is defined.

By examining the higher-order function that calls the callback, we can determine the "this" value in the callback. The actual definition of the enclosing function may include locally scoped properties, which is the main cause of this problems in callbacks. However, since the callback's context changes dynamically depending on how it is called, when the property is accessed via the "this" binding in the callback, it does not exist.

Now we will learn how to access the correct "this" in the callback.

Use "self" mode

Creating a variable named self and assigning it a this value within the scope of the declared function is a typical pattern. We can achieve the desired behavior by creating a new variable called self (or any other valid variable name will do) and giving it the value "this".

Example

<html>
<body>
   <h2> 'this' Inside a Callback using the <i> 'self' pattern </i> </h2>
   <button onclick="myFunction()"> Click here </button>
   <div id="root" style="
      background-color: rgb(240, 248, 255);
      border: 1px solid gray;
      margin: 5px 0px;
      padding: 10px;
   ">
      Welcome to Tutorialspoint!
   </div>
   <script>
      const root = document.getElementById('root')
      function myFunction() {
         this.variable = 'I am this variable'
         const variable = 'I am a const variable'
         const self = this
         setTimeout(() => {
            root.innerHTML = this.variable + '<br/>'
            root.innerHTML += variable
         }, 1000)
      }
   </script>
</body>
</html>
Copy after login

Use arrow functions

ECMAScript 6 saw the debut of JavaScript arrow functions. They have no bindings of their own and are a cleaner alternative to traditional function expressions. This ensures that if this is referenced inside an arrow function, it is searched in scope as a regular variable.

Example

<html>
<body>
   <h2> 'this' Inside a Callback using the <i> arrow function </i> </h2>
   <button onclick="myFunction('ABC')"> Click here </button>
   <div id="root" style="
      background-color: rgb(240, 248, 255);
      border: 1px solid gray;
      margin: 5px 0px;
      padding: 10px;
   ">
      Welcome to Tutorialspoint!
   </div>
   <script>
      const root = document.getElementById('root')
      function myFunction(name) {
         this.name = name
         let obj = {
            run: function(callback) {
               setTimeout(callback, 1000)
            },
         }
         obj.run(() => {
            root.innerHTML = this.name
         })
      }
   </script>
</body>
</html>
Copy after login

Use another variable to store the "this" object

The object is linked to it, which is usually the object we actually want to access when we try to access it in the callback. Creating a variable and storing its value before the callback scope is one way to achieve this (although some programmers are reluctant to do this because it looks confusing).

Some people refer to it as "that" or "self", but as long as the terminology is clear, it doesn't matter. This workaround works great because the variable meets the lexical scope requirements and can therefore be used in the callback. You still have access to the callback's dynamic this binding, which is another benefit of this approach.

Example

<html>
<body>
   <h2>
      'this' Inside a Callback using the
      <i> another variable to store the 'this' object </i>
   </h2>
   <button onclick="myFunction('XYZ')"> Click here </button>
   <div id="root" style="
      background-color: rgb(240, 248, 255);
      border: 1px solid gray;
      margin: 5px 0px;
      padding: 10px;
   ">
      Welcome to Tutorialspoint!
   </div>
   <script>
      const root = document.getElementById('root')
      function myFunction(name) {
         this.name = name
         let that = this
         let obj = {
            run: function(callback) {
               setTimeout(callback, 1000)
            },
         }
         obj.run(function() {
            root.innerHTML = this.name
         })
      }
   </script>
</body>
</html>
Copy after login

Use explicit binding of this to the object

When we define a callback, we can declare what we want. We can set the "this" value using the bind() method and ensure that it stays that way throughout the function execution, regardless of how or where it is called or passed.

The bind() method is available in every function and creates a new function using the "this" property connected to the given object. The only difference between the returned function and the original function is that you have complete control over what the "this" attribute points to.

Example

<html>
<body>
   <h2>
      'this' Inside a Callback using
      <i> explicitly binding this to an object </i>
   </h2>
   <button onclick="myFunction('Tutorialspoint')"> Click here </button>
   <div id="root" style="
      background-color: rgb(240, 248, 255);
      border: 1px solid gray;
      margin: 5px 0px;
      padding: 10px;
   ">
      Welcome to Tutorialspoint!
   </div>
   <script>
      const root = document.getElementById('root')
      function myFunction(name) {
         this.name = name
         let callbackFunction = function() {
            root.innerHTML = this.name
         }.bind(this)
         let obj = {
            run: function(callbackFunction) {
               setTimeout(callbackFunction, 1000)
            },
         }
         obj.run(callbackFunction)
      }
   </script>
</body>
</html>
Copy after login

The above is the detailed content of How do I access the correct 'this' in the callback?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!