Understanding this in JavaScript

A beginner-friendly guide to this in function calls, object methods, timers, call/apply, and arrow functions.

🎯 Introduction

This article explains one of JavaScript's most important and often confusing concepts: how this is determined. You will learn what this represents, which object it refers to in different situations, and how call and apply set its value. You will also explore timers and callbacks, and see how arrow functions capture this. Understanding these rules helps prevent binding mistakes and makes debugging easier.


🔍 What Is this, and What Does It Refer To?

In JavaScript, this is a special keyword representing the “owner” of the current execution context. Put simply, it refers to the context object associated with the executing code.

Consider an everyday analogy:

When you cook at home, you are the host. When you cook at a friend's house, you are still the same person, but the kitchen belongs to someone else and different rules apply.

Similarly, the value of this depends on how a function is called and its execution context.

The value of this is not fixed; it can change with the calling context. To understand it, examine how the function is invoked.

🔥 this in a Direct Function Call

Consider calling a regular function directly:

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

What does this refer to here?

  • In a browser, in non-strict mode, this refers to the global object, window.
  • In strict mode, this is undefined.

There is no object receiver in this call, so the default is the global object in non-strict mode, or undefined in strict mode. For a global function in a classic non-strict browser script, show() and window.show() produce the same this value.

Seeing window or undefined can be confusing at first. Remember that a direct call to a regular function uses the global object or undefined, depending on strict mode.

🐻 this in an Object Method Call

When a regular function is called as an object method, this refers to the object receiving the call.

For example:

const person = {
    name: 'Ming',
    sayHi: function () {
        console.log('Hi, I am', this.name);
    },
};
person.sayHi();

In person.sayHi(), this refers to person, so the output is:

Hi, I am Ming

An everyday analogy:

“This house looks beautiful!” At home, “this house” means your house. At a friend's home, it means theirs.

In a regular method call, this refers to the object on which the method is called.

⏰ this in Timers and Callbacks, Such as setTimeout

Timers and callbacks often make this confusing:

const obj = {
    name: 'Hong',
    greet: function () {
        setTimeout(function () {
            console.log(this.name);
        }, 1000);
    },
};
obj.greet();

The example is intended to demonstrate a missing object property, with the result shown as undefined.

The callback is invoked separately from obj.greet, so it does not retain obj as its receiver. In a browser, setTimeout invokes a regular callback with window as this; the logged value therefore comes from window.name, rather than obj.name.

To access obj through this in the callback, you need to preserve that context explicitly.


✂️ Setting this with call and apply

JavaScript provides call and apply to explicitly set the value of this when invoking a function.

function sayHello() {
    console.log('Hello, I am', this.name);
}

const user = { name: 'Zhang' };
sayHello.call(user); // Hello, I am Zhang
sayHello.apply(user); // Hello, I am Zhang

The difference is how arguments are passed:

  • call takes comma-separated arguments, such as call(user, 25, 'Beijing').
  • apply takes an array of arguments, such as apply(user, [25, 'Beijing']).
With call and apply, a regular function can run with a specified object as this, much like an object method.

🚀 this in Arrow Functions

Arrow functions are covered in the ES6 course; we will revisit them there.

Unlike regular functions, arrow functions do not have their own this. They capture this from the enclosing scope, such as an enclosing function.

For example:

const obj = {
    name: 'Qiang',
    greet: function () {
        const arrow = () => {
            console.log(this.name);
        };
        arrow();
    },
};
obj.greet(); // Prints: Qiang

The arrow function captures the enclosing method's this, which is obj.

An everyday analogy:

An arrow function is like an assistant who follows the lead of the enclosing function instead of adopting a new identity.

Arrow functions cannot be used as constructors, and call or apply cannot change their this value.

❓ Knowledge Check

Q1: How does this differ in regular functions and arrow functions? A regular function's this is determined when it is called. An arrow function captures the enclosing scope's this when it is created.

Q2: Why does a setTimeout callback not automatically use the object's this? The callback is invoked separately, so it does not retain the object as its receiver. A regular browser timer callback receives the global object; preserving the original object requires an explicit technique.

Q3: What is the difference between call and apply?call takes comma-separated arguments; apply takes an array. Both can specify this for regular functions.


🧪 Exercises

  1. Modify this code so the setTimeout callback uses person as this. Hint: use an arrow function.
const person = {
    name: 'Bai',
    sayHi: function () {
        setTimeout(function () {
            console.log(this.name);
        }, 500);
    },
};
person.sayHi();
  1. Invoke greet with call or apply so that this refers to the object below.
function greet() {
    console.log('Hello, ' + this.name);
}

const user = { name: 'Hong' };

// Call greet here with user as this

🎉 You now understand the basic rules for this, how to use call and apply, and how arrow functions capture this! Keep practicing to build your JavaScript skills.