JavaScript: This and That

JavaScript is an interesting language, but can also be frustrating. It's ability to do so many powerful operations rather easily is something to be praised, but some of the ways it handles those operations can become extremely frustrating if you don't fully understand why it's happening. This post is aimed at explaining one of those more frustrating concepts.


This concept is oftentimes confused with scope because they seem somewhat similar, but in practice are vastly different. Scope refers to the range that a variable or function or object can be accessed from. Or the range of effect of that item. Scope starts at the "window" object of the browser, and traverses downward into the specific function or module that the item exists within. Accessibility works in an upwards fashion as well. A parent-child relationship. The children can access the information from the parent, but the parent cannot access information from the child scope. This is best explained through code, and I'll provide that here.

// window scope   
var alpha = "omega";  
function foo () {  
  // foo scope  
  var beta = "theta";  
} foo();  
console.log(alpha);  // has access, logs omega  
console.log(beta);   // has no access, logs undefined  

Ok, so now that scope is out of the way what makes context different? Well context refers to what "this" refers to at the current call time. "This" is a keyword that refers to the current object within the current scope. This is common with multiple languages and allows for a lot of things to be handled with less coding involved such as...

$('#patient').on('click', function() {   
  $(this).addClass('zero'); // "this" refers to #patient  

Where does "that" come in then you may wonder. Well "that" became a common word used to access "this" from a separate scope. It's a sort of a common convention to name the variable "that" in order to represent that it is referring to a "this" from somewhere else. Let's take a look at this in practice.

var that = $(this);    // "that" now refers to the window object  
$('#first').on('click', function() {  
  console.log($(this)); // "this" is referring to #first
  console.log(that);    // but "that" is still referring to the window object

Since it's just a convention though, you can use what ever name you want to. Just make sure that it's consistent throughout your code. A lot of programmers will use "self" as the variable name referring to "this". Or they will name the variable after the element or object "this" is referring to. In my opinion the second option is the more readable way for naming since you can easily see exactly what "this" is referring to.

Anyway, this post has gotten quite long, so I'm going to end it here. Hopefully it has been of some use if you've been curious about this concept. And as always, please leave your thoughts or comments below. If you find an error in my post please leave that as well.

comments powered by Disqus