What is the `this` keyword in JavaScript?

In this shot, we will go over the this keyword in JavaScript.

First, we need to understand the difference between a function and a method.

Functions

A function is a stand-alone block of code that performs a particular task.

Example

function sayHello() {
console.log("Hello")
}
sayHello(); // Hello

Methods

A method is also a function, but it is inside an object.

Example

const person = {
name: "John",
sayHello: function(){
console.log("Hello");
}
}
person.sayHello() // Hello

The this keyword

So, if this is inside a method, this will refer to the object itself.

Example

const person = {
name: "John",
sayHello: function(){
console.log(this);
}
}
person.sayHello();

If this is inside a function, this will refer to the global object, which is the window object in Browsers and the global object in Node.

Example

function sayHello(){
console.log(this);
}
sayHello();

The constructor function

We use a constructor function to create a blueprint of an object. The this keyword will refer to the created object.

The new keyword creates a new empty object { }.

Example

function Person(name) {
this.name = name;
this.log = function(){
console.log(this);
}
}
const p1 = new Person("John");
const p2 = new Person("Doe");
p1.log();
p2.log();

Code example

Consider the code below and try to guess what this will refer to.

Consider the code below and try to guess what this will refer to.

Q
const person = {
  fName: "John",
  skills: ["HTML", "CSS", "JS"],
  logSkills: function(){
    this.skills.forEach(function(skill){
      console.log(`${this.fName} can do ${skill}.`)
    })
  }
}

person.logSkills();
A)
John can do HTML
John can do CSS
John can do JS
B)
undefined can do HTML
undefined can do CSS
undefined can do JS

Try it yourself by pressing the Run button.

const person = {
fName: "John",
skills: ["HTML", "CSS", "JS"],
logSkills: function(){
this.skills.forEach(function(skill){
console.log(`${this.fName} can do ${skill}.`)
})
}
}
person.logSkills();

Explanation

this is inside an objective method, and an objective method is just a regular function, so this refers to the window object.

That’s why we tend to use Arrow Functions as callback functions, as they do not have their own bindings to this.

Now, when we substitute a regular callback function with an Arrow Function, we get the expected results.

const person = {
fName: "John",
skills: ["HTML", "CSS", "JS"],
logSkills: function(){
this.skills.forEach((skill)=>{
console.log(`'${this.fName}' can do '${skill}'.`)
})
}
}
person.logSkills();

Free Resources

Attributions:
  1. undefined by undefined