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 id="this-Inside-a-Callback-using-the-i-self-pattern-i"> '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>
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 id="this-Inside-a-Callback-using-the-i-arrow-function-i"> '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>
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>
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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
