Dark mode switch icon Light mode switch icon

This in javascript

2 min read

In this post we will explore what this keyword refers under various conditions and there by understand the keyword and how it works in javascript.

The this keyword can point to

this within method of an object - no arrow function

const obj = {
    name: "obj",
    printName() {
        console.log(this.name);
    },
    printObj() {
        console.log(this); // this refers to the object `obj`
    }
}
obj.printName() // obj
obj.printObj() //{name: "obj", printName: ƒ, printObj: ƒ}

this within method of an object - arrow function

The value of this in an arrow function is always the value of this in the parent non arrow function.

const obj = {
    name: "obj",
    printObj: () => {
        console.log(this); // this refers to the window
    }
}
obj.printObj() // Window {window: Window, self: Window, document: document, name: "", location: Location, …}

this within function body

function greet() {
    console.log(this);
}
greet(); // Window {window: Window, self: Window, document: document, name: "", location: Location, …}

this when new keyword is used

function Game(inTitle) {
    this.title = inTitle;
    console.log(this); // Game {title: "pong"}
}

const game = new Game("pong");

this within callback in a method of an object - no arrow function

const fruits = {
    name: "fruits",
    fruits: ["apple", "mango", "banana"],
    printFruits() {
        console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ}
        this.fruits.forEach(function(fruit) {
            console.log(this); // Window {window: Window, self: Window, document: document, name: "", location: Location, …} * 3 times
        })
    }
}

fruits.printFruits();

this within callback in a method of an object - arrow function

const fruits = {
    name: "fruits",
    fruits: ["apple", "mango", "banana"],
    printFruits() {
        console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ}
        this.fruits.forEach((fruit) => {
            console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ} * 3 times
        })
    }
}

fruits.printFruits();

Originally published on by Rakshith Bellare