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

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

Barbara Streisand
Release: 2024-12-02 10:51:11
Original
289 people have browsed it

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

What Does the 'var that = this;' Syntax Accomplish in JavaScript?

In JavaScript, it is common to encounter code blocks similar to the following:

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

This syntax assigns the value of this to a variable named that. The purpose of this idiom is to preserve a reference to the correct this context within nested functions.

To illustrate the need for that, consider the following example:

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

    var that = this;

    colours.forEach(function() {
        // this is undefined
        // that is a reference to the element clicked on
    });
});
Copy after login

Within the anonymous function passed to forEach, the this keyword no longer refers to the clicked element because its scope has changed. Assigning this to that allows us to retain the desired reference within the nested function.

$('#element').click(function(){
    // this is a reference to the element clicked on

    var that = this;

    $('.elements').each(function(){
        // this is a reference to the current element in the loop
        // that is still a reference to the element clicked on
    });
});
Copy after login

In practice, it is beneficial to use a more descriptive alias for this to enhance code readability. For instance, in the examples above, clickedEl would be a more suitable choice.

The above is the detailed content of Why Use `var that = this;` in JavaScript Nested 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