The meaning of “This” and “That” in Javascript

Intro

In Javascript “this” is a special keyword which often confuses developers. You’ll often see a variable of “that” within methods which have a value of the mysterious “this” Discussing the meaning of “this” might sound philosophical, in Javascript “this” is actually not as ambiguous as it seems. In short:

“this” is a reference point to what is calling a function. It’s a reserved Javascript keyword

“that” is a variable used to to pass scope to private methods. It’s not part of the language but is a popular Javascript “design pattern” (which makes up for what many believe is an error in the Javascript specification).

The “this” keyword explained

Using this is very handy when referring to values within an object. Understanding how it’s use is essentially to writing clean, efficient code. Let’s look at the usage of the this keyword in practice.

var ourFunction = function () {
	console.log(this);
};
ourFunction(); 

What this will do is log the Window object to our console. This is because ourFunction() is being called from the root, or the Window object in your browser.

Lets call this from within an method inside another object.

var ourObject = {}

ourObject.ourMethod = function(){
	console.log(this);
}
ourObject.ourMethod()

this is no longer the Window object. It’s ourObject, since that’s what’s calling it. Or as the MDN puts it:

“Use the this keyword to refer to the current object. In general, this refers to the calling object in a method”.

Don’t be confused by the word “this”

I find the word “this” little counter intuitive. If I were to say “THIS is my house” while standing inside my actual house, by Javascript logic, my house would belong to the root, Earth.

If I were to wrap my house inside a my city, my house would belong to the city, since that’s what’s calling it.

var newYork = {}

newYork.myHouse = function(){
	console.log(this);
	console.log("is my house");
}

newYork.myHouse();
// Object {myHouse: function}. I guess New York actually owns my house. Bummer.

Why we use “that”

You might run into a few problems when trying to pass defined values …

Read More»