Question:

Describe the function of the this keyword and use at least one example to demonstrate how it works.


Most people new to JavaScript can’t wrap their head around what this actually is and how it works leading them to use solutions that don’t keep the code base clean. I will explain what this is by the use on an example below.

This: What is it?

When a function is invoked an execution context is created. This context holds a reference of the function, parameters etc. What it also contains is this reference based on the call-site of the function.

this is a binding that we can use to allow us access to other object’s methods(functions are objects too) or properties without having to repeat our code. There seems to be a lot of confusion that this refers to the function that invoked it but that simply is not true.

function foo() {
 console.log(this.a); 
}

var person = {
  a:4            
}

foo(); // output: I'm Global
foo.call(person); //output: 4 

The example above shows that when we invoke foo -foo()- this is not referring to the foo function itself because if it was we would have got undefined back.

function foo () {
 console.log(foo.a); // changed "this" to foo to illustrate that "this" is not bound to function 
}

var a = "I'm Global."

foo(); //output: undefined

Now you might be wondering well why does “this” point to the global variable in the first place. Well JavaScript sees global variables that have the same name as object properties to be the same thing and not a copy.

Another reason is because when we call foo like this foo() we are applying the default binding to this. We know that it is using the default binding by inspecting the call-site foo()- it is a plain undecorated function reference.

Another example below shows the usefulness of the this bind.

function logAgeName() {
  console.log("Logged: " + this.name + " " + this.age);
}

function Person(name,age) {
   this.name = name;  
   this.age = age;
}

var oscar = new Person ("Oscar",27); // create "oscar" object with constructor

logAgeName.call(oscar); // use call to bind logAgeName "this" with oscar object

As you can see it’s very quick and clear what we did above. We used an object constructor to create “oscar”. Since we used new in the creation that this reference is bound to that function(don’t worry to much about this). Then we call logNameAge to point this to oscar so it can carry out its code block. This make it easy to create another person say “jane” and do the same thing without changing a lot of code.

There is a lot to cover over on how to use the this but I will leave it off here for another article. The main thing to take away is that this in created for every function in the execution context and that the reference where it points to is dependent on its call-site. The usefulness of this comes when we want to use a function over without having to break or copy code to get the same result.