In a JavaScript file I saw:
function Somefunction(){ var that = this; ... }
What is the purpose of declaring that
and assigning this
this to it?
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).
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).
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With