Understand this in JavaScript Through a Simple Story

Understand What this Is Through a Simple Story

Joe and Alex are a married couple. They live at 34 Street. One day, Joe or Alex says, “This house is too old and needs to be renovated!” You can see that this refers to the home where Joe and Alex live, meaning “34 Street.”

But suppose the person calling this today is not Joe or Alex, but another family. Then this would refer to “another home,” not “34 Street.” The concept in this story is actually exactly the same as JavaScript’s this!

What Is this

Simply put, whoever calls this, this refers to that caller.

In JavaScript, this can be used in the global scope and in function execution contexts. In addition, this also behaves differently in strict mode🔗. Below are four usage scenarios.

Using this directly in the global scope or using this inside a function is not particularly meaningful (methods one and two); it is enough to be aware of them.

1. Using this in the Global Scope

If you print this directly, it will be window when executed in a browser and global when executed in node.js.

console.log(this === window); // true

2. Using this in a Function

In non-strict mode🔗, this points to the global object, namely window or global. This is because the execution environment (such as a browser) treats it as if you were referring to window.calledFunction.

function show() {
console.log(this === window); // true
}
show();

But in strict mode, this will be undefined, preventing this from unexpectedly accessing the global object. This is true even inside nested functions.

'use strict';
function show() {
console.log(this === undefined);
}
show();

3. Using this in a Method

A child who goes to school is called a “student”; a function inside an object is called a “method.” If a method is called, JavaScript points this to the object that owns that method.

function sayName() {
return `My name is: ${this.name}`;
}
const me = {
name: 'Joe',
sayName,
};
const you = {
name: 'Alex',
sayName,
};
me.sayName(); // Joe
you.sayName(); // Alex

4. Using this in a Constructor

When using the new keyword to create a new object, JavaScript points this to the object that belongs to that method.

function Student(name) {
this.name = name;
}
const student = new Student('Joe');
console.log(student.name); // Joe

Specifying this

The four usage scenarios were mentioned above, but sometimes you need to manually specify the value of this. In that case, you can use the three methods call(), apply(), and bind().

Summary

this is confusing because it must be determined from context. The simplest rule is: whoever calls this, this refers to that caller.

References