Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'var that = this;' mean in JavaScript?

In a JavaScript file I saw:

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

What is the purpose of declaring that and assigning this this to it?

like image 557
Chris Avatar asked Feb 03 '11 13:02

Chris


People also ask

What does VAR means in JavaScript?

Definition and Usage The var statement declares a variable. Variables are containers for storing information. Creating a variable in JavaScript is called "declaring" a variable: var carName; After the declaration, the variable is empty (it has no value).

Do we need to use var that this JavaScript?

The var keyword is never "needed". However if you don't use it then the variable that you are declaring will be exposed in the global scope (i.e. as a property on the window object).

What does _( Variable_name mean in JavaScript?

Using _(...) with function syntax implies that _ is a function. That said, it is commonly used by the underscore. js library, however if you're looking at minified code, it's quite possibly being used as another single-character variable name to save on file size.

Why do we need VAR in JavaScript?

Before ES6, the var keyword was used to declare a variable in JavaScript. The var keyword has been around since the inception of JavaScript, and it's what you will see in any pre ES6 code. Variables declared using the var keyword are either globally or functionally scoped, they do not support block-level scope.


1 Answers

I'm going to begin this answer with an illustration:

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

My answer originally demonstrated this with jQuery, which is only very slightly different:

$('#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     }); }); 

Because this frequently changes when you change the scope by calling a new function, you can't access the original value by using it. Aliasing it to that allows you still to access the original value of this.

Personally, I dislike the use of that as the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I always use a more descriptive alias. In my examples above, I'd probably use clickedEl.

like image 87
lonesomeday Avatar answered Sep 28 '22 23:09

lonesomeday