/ / What Exactly Is “this” Keyword in JavaScript?

What Exactly Is “this” Keyword in JavaScript?

JavaScript this keyword

JavaScript’s this keyword can be a hard nut to crack. However, taking time to understand it will unlock your ability to tackle advanced programming concepts.

In this article, you will learn the essentials about this in simple terms.

Let’s start things off by understanding what JavaScript’s this keyword references.

What does “this” mean in JavaScript?

In most cases, JavaScript’s this keyword refers to the object that owns the method containing the keyword this.

So what exactly does this mean? Let’s see with some examples.

Example 1: What object owns “this” keyword’s method?

const myBio = {
  firstName: "Oluwatobi",
  lastName: "Sofela",
  fullName: function() {
    console.log(`${this.firstName} ${this.lastName}`);
  }
};

myBio.fullName();

// The invocation above will return:
"Oluwatobi Sofela"

Try it on StackBlitz

In the snippet above, observe that the keyword this is in the fullName method. And the object that owns fullName is myBio.

Therefore, the keyword this inside fullName refers to myBio.

In other words, this.firstName and this.lastName are equivalent to myBio.firstName and myBio.lastName.

As such, the myBio.fullName() code correctly returned "Oluwatobi Sofela".

Example 2: What object owns “this” keyword’s method?

const myBio = {
  firstName: "Oluwatobi",
  lastName: "Sofela",
  myName: {
    firstName: "Tobi",
    lastName: "Sho",
    fullName: function() {
      console.log(`${this.firstName} ${this.lastName}`);
    }
  }
};

myBio.myName.fullName();

// The invocation above will return:
"Tobi Sho"

Try it on StackBlitz

In the snippet above, observe that the keyword this is in the fullName method. And the object that owns fullName is myName.

Therefore, the keyword this inside fullName refers to myName.

In other words, this.firstName and this.lastName are equivalent to myName.firstName and myName.lastName.

As such, the myBio.myName.fullName() code correctly returned "Tobi Sho".

Example 3: What object owns “this” keyword’s method?

const myBio = {
  firstName: "Oluwatobi",
  lastName: "Sofela",
  fullName: function() {
    console.log(`${this.firstName} ${this.lastName}`);
  }
};

window.setTimeout(myBio.fullName, 100);

// The invocation above will return:
undefined undefined

Try it on StackBlitz

In the snippet above, observe that the keyword this is in the fullName method. But, notice that we passed myBio.fullName and 100 to the window object’s setTimeout() method.

Therefore, the window object becomes the owner of the fullName method.

Consequently, the keyword this inside fullName refers to the global window object.

In other words, this.firstName and this.lastName are equivalent to window.firstName and window.lastName.

However, since window does not have any firstName and lastName property defined in it, the window.setTimeout(myBio.fullName, 100) code correctly returned undefined undefined.

Example 4: What object owns “this” keyword’s method?

// Define four (4) objects:
const firstName = { myBio: "Oluwatobi" };
const lastName = { myBio: "Sofela" };
const companyName = { myBio: "CodeSweetly" };
const companyWebsite = {
  myBio: "www.codesweetly.com",
  myWebsite: function(func) {
    return func.bind(this)(); 
    // bind() used to reassign func to companyWebsite
  }
};

// Define two (2) functions:
function displayName() {
  console.log(this.myBio);
}

function fullName() {
  console.log(`${this.firstName} ${this.lastName}`);
}

// Add an aboutMe property to three (3) of the objects above and the global window object:
firstName.aboutMe = displayName;
lastName.aboutMe = displayName;
companyName.aboutMe = displayName;
window.aboutMe = displayName;

// Invoke aboutMe() and myWebsite() methods:
firstName.aboutMe(); // “Oluwatobi”
lastName.aboutMe(); // “Sofela”
companyName.aboutMe(); // “CodeSweetly”
window.aboutMe(); // undefined
companyWebsite.myWebsite(displayName); // “www.codesweetly.com”
companyWebsite.myWebsite(fullName); // undefined undefined

Try it on StackBlitz

In the snippet above, the specific object the keyword this referenced varied based on what owns its function.

Important stuff to know about “this” keyword

Keep these four essential pieces of info in mind whenever you choose to use the keyword this. They will save you a lot of debugging time.

Info 1: Beware of an arrow function’s “this” keyword!

Remember always that arrow functions do not have their own this binding.

Therefore, the keyword this in an arrow function does not refer to the object that owns the function. Instead, it references the this value of the arrow function’s enclosing lexical context.

So what exactly does this mean? Let’s see with some examples.

Example 1: What is the “this” value of the arrow function’s lexical context?

const myBio = {
  firstName: "Oluwatobi",
  lastName: "Sofela",
  fullName: () => {
    console.log(`${this.firstName} ${this.lastName}`);
  }
};

myBio.fullName();

// The invocation above will return:
undefined undefined

Try it on StackBlitz

In the snippet above, observe that the keyword this is in the fullName() arrow function. And the lexical context of the function is myBio.

As such, fullName’s this keyword refers to myBio’s this value. And myBio’s this value is the window object.

In other words, this.firstName and this.lastName are equivalent to window.firstName and window.lastName.

Therefore, since window does not have any firstName and lastName property defined in it, the myBio.fullName() code correctly returned undefined undefined.

Note

fullName’s this keyword does not refer to myBio — it references myBio’s this value.

Example 2: What is the “this” value of the arrow function’s lexical context?

const myBio = {
  firstName: "Oluwatobi",
  lastName: "Sofela",
  fullName: function() {
    setTimeout(() => {
      console.log(`${this.firstName} ${this.lastName}`);
    }, 100);
  }
};

myBio.fullName();

// The invocation above will return:
"Oluwatobi SOfela"

Try it on StackBlitz

In the snippet above, note that this is inside an anonymous arrow function that setTimeout will invoke after 100 milliseconds. And the lexical context of the arrow function is fullName.

When setTimeout invokes the arrow function, its this keyword will refer to fullName’s this value. And fullName’s this value is the myBio object.

In other words, this.firstName and this.lastName are equivalent to myBio.firstName and myBio.lastName.

Therefore, the myBio.fullName() code correctly returned "Oluwatobi Sofela".

Note

The arrow function’s this keyword does not refer to fullName — it references fullName’s this value.

Info 2: What is “this” keyword’s value outside a method?

When this gets used outside a method, it will refer to the global Window object.

Here are some examples:

Example 1: What object does a function’s “this” keyword reference?

function myObjectIs() { 
  return this;
}

console.log(myObjectIs());

// The invocation above will return:
Window

Try it on StackBlitz

The keyword this in the myObjectIs() function above refers to the global Window object because we did not use it within a method.

Example 2: What object does a variable’s “this” keyword reference?

const myObjectIs = this;

console.log(myObjectIs);

// The invocation above will return:
Window

Try it on StackBlitz

The keyword this in the myObjectIs variable above refers to the global Window object because we did not use it within a method.

Example 3: What object does a properties object’s “this” keyword reference?

const myObjectIs = { theGlobal: this };

console.log(myObjectIs.theGlobal);

// The invocation above will return:
Window

Try it on StackBlitz

The keyword this in the myObjectIs.theGlobal property above references the global Window object because we did not use the keyword within a method.

Example 4: What object does an array’s “this” keyword reference?

const myObjectIs = [this];

console.log(myObjectIs[0]);

// The invocation above will return:
Window

Try it on StackBlitz

The keyword this in the myObjectIs[0] array above references the global Window object because we did not use the keyword within a method.

Info 3: What is “this” keyword’s value in strict function mode?

If you use the this keyword in a function in strict mode, its value will default to undefined.

Here are some examples:

Example 1: What is “this” keyword’s value in regular function mode?

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

checkValue();

// The invocation above will return:
Window

Try it on StackBlitz

In the snippet above, note that checkValue() is not in strict mode, and we called it in the global context.

As such, the function’s this keyword refers to the global Window object.

Example 2: What is “this” keyword’s value in strict function mode?

function checkValue() {
  "use strict";
  console.log(this);
}

checkValue();

// The invocation above will return:
undefined

Try it on StackBlitz

In the snippet above, note that checkValue() got defined in strict mode, and we called it in the global context.

As such, the function’s this keyword default to undefined.

Note

When used outside any function, the keyword this will reference the global window object — regardless of whether it got used in strict mode or not.

Info 4: You can change the value of a function’s “this” keyword

Suppose you want the keyword this in a specific function to reference another object. In such a case, use call(), apply(), or bind() to change the runtime binding of the keyword’s function from its lexical (definition) object to any other object of your choice.

For instance, consider the JavaScript code below:

// First object:
const firstName = {
  myName: "Oluwatobi",
  showMyName: function() {
    console.log(this.myName);
  }
};

// Second object:
const lastName = {
  myName: "Sofela",
};

// Let showMyName’s this keyword refer to the lastName object:
firstName.showMyName.call(lastName);

// The invocation above will return:
"Sofela"

Try it on StackBlitz

In the snippet above, we used call() to change the runtime binding of showMyName from the object in which it was defined (firstName) to a different object of our choice (lastName).

As such, showMyName’s this keyword refers to the lastName object.

Therefore, firstName.showMyName.call(lastName)’s invocation correctly returned “Sofela”.

Wrapping it up

The meaning of JavaScript’s this keyword depends on its execution context.

When this is in a method, it will reference the object that owns the method’s definition.

When the keyword this is in an arrow function, it will refer to the this value of the function’s enclosing lexical context.

Suppose you use this outside a function. In such a case, it will refer to the global Window object.

Overview

This article discussed what the keyword this means in JavaScript. We also looked at what it references in various execution contexts.

Thanks for reading!

Credit

Featured Image by Zachary Keimig

Get Notified of the Latest Publications

Similar Posts