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; ... }
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 }); });
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!