Last updated on February 28, 2020
Guys, this time I would like to share with you widely used one simple concept within JavaScript.
Most experienced JavaScript developers are also sometimes lagging to understand what’s actually happening in this case. So will check out elaborately down for when to use ‘var that = this’ in javascript.
Introduction
I wish I would’ve known this thing when I started my career earlier but finally, I sorted out that saved much time later part. Why am I stressing this piece here is that basics are the basics. This will fit everything in learning.
Now you’ll come to know after seeing the below code snippet what I’m really talking about
function getUserName() {
var that = this;
};
The above one seems very simple but if we fail to understand this then we will start to face issues in our project.
The concept behind ‘var that = this;‘
Basically, functions are scoped to global
in JavaScript. This we call it as Function Invocation pattern.
let’s take from the above code snippet, we can access the function name getUserName() from global window object like window.getUserName()
Method pattern
When a function is assigned to a property of an object then that would be Method. Here getName function scoped to User Object.
const User = {
firstName: 'John',
lastName: 'Smith',
getName: function () {
return `${this.firstName} ${this.lastName}`;
}
};
Function pattern
Let’s take the same code snippet from method pattern, that we can rewrite as
const User = {
firstName: 'John',
lastName: 'Smith',
getName: function () {
const styledName = function ()
{
return `©©©${this.firstName} ${this.lastName}©©©`;
};
return styledName ();
}
};
User.getName();
The last line from the above snippet, we’ll get an error firstName and lastName will be undefined.
Guess what??? That’s because of styledName
function is scoped to global
.
If we search both firstName & lastName properties within window global Object which doesn’t exist. Typically it’s existing inside User Object.
This is the situation where we ended up using var that = this;
If we want to rewrite the getName method then it would be,
getName: function () {
const that = this;
const styledName = function ()
{
return `©©©${that.firstName} ${that.lastName}©©©`;
};
return styledName ();
}