Home > Web Front-end > JS Tutorial > Why Use `var that = this;` in Nested JavaScript Functions?

Why Use `var that = this;` in Nested JavaScript Functions?

Linda Hamilton
Release: 2024-12-05 05:50:10
Original
292 people have browsed it

Why Use `var that = this;` in Nested JavaScript Functions?

Accessing this in Nested Functions: Unraveling var that = this;

In JavaScript, understanding the scope and value of this is crucial. Consider the following code snippet:

function Somefunction() {
  var that = this;
  ...
}
Copy after login

Why is that declared and assigned the value of this?

To comprehend the purpose of this technique, let's visualize a scenario:

var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
  // this points to the clicked element
  var that = this;

  colours.forEach(function() {
    // this is undefined within this inner function
    // that still refers to the clicked element
  });
});
Copy after login

this within the forEach callback refers to the current array element, not the clicked element. However, that maintains a reference to the clicked element.

When you move into nested functions, the scope of this can change, making it difficult to access the original value. Aliasing this to that ensures that the original value is still accessible.

Note that using that as an alias is not always optimal. It's better to use a more descriptive alias that clearly indicates what it refers to, especially in complex functions.

The above is the detailed content of Why Use `var that = this;` in Nested JavaScript Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template