What is the `this` keyword in JavaScript?

Think of a tour guide leading different groups through a museum. When the guide says, “I will show you the next exhibit,” the “I” always refers to the guide currently speaking, regardless of which group they are leading. Similarly, this keyword dynamically refers to the object currently “leading” the operation in JavaScript. Its meaning changes based on where and how it’s used, just like how the guide’s “I” depends on the tour context.

What does this keyword mean?

this is a special keyword in JavaScript that refers to an object. But what object it refers to changes depending on the context. It can point to the global window object, the object calling a function, or something else.

Let’s look at some examples:

The this keyword in an object method

When this is used inside a method (a function inside an object), it refers to the object that owns the method.

const person = {
name: "Alice",
greet: function () {
console.log(`Hello, my name is ${this.name}`);
},
};
person.greet(); // Output: Hello, my name is Alice

Explanation: this.name points to the name property of the person object because the greet function is called from person.

The this keyword in the global context

When this is used outside any function or object, it refers to the global object. In browsers, the global object is called window.

console.log(this); // In browsers, this points to the window object

Explanation: Here, this refers to the global environment, which contains properties and methods available throughout the code.

While this points to the global object in browsers when used outside any function, its behavior changes significantly when used inside a function. Let’s see how.

The this keyword in a function

By default, when we use this in a regular function, it refers to the global object.

function showThis() {
console.log(this);
}
showThis(); // Output: window (in non-strict mode)

Explanation: In non-strict mode, this points to the global object inside functions. But if strict mode is enabled, this will be undefined unless explicitly set.

The this keyword in strict mode

Strict mode changes how this works. In strict mode, this inside a function does not point to the global object. Instead, it remains undefined unless explicitly set.

"use strict";
function showThis() {
console.log(this);
}
showThis(); // Output: undefined

Explanation: Strict mode helps prevent mistakes and makes code safer. It disables the default global binding for this.

Note: In browsers, this in the global scope refers to the window object, while in Node.js, it refers to the global object, making it environment-dependent.

The this keyword in event handlers

In event handlers, this refers to the element that triggered the event.

document.querySelector("button").addEventListener("click", function () {
console.log(this); // Refers to the button element
});

Explanation: Here, when the button is clicked, this refers to the button that caused the event. This helps to work with the specific element in code.

Explicit binding with call, apply, and bind

We can explicitly set the value of this for a function using call, apply, and bind. These methods allow us to control the context (this) in which a function is executed, which is especially useful when the default value of this doesn’t behave as expected.

call()

The call method invokes a function and explicitly sets this value. It accepts this value as its first argument, followed by individual function arguments.

function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const person = { name: "Alice" };
greet.call(person, "Hello", "!"); // Output: Hello, Alice!

Explanation: this inside the greet function is explicitly set to the person object.

apply()

The apply method works similarly to call, but instead of passing arguments individually, you pass them as an array.

greet.apply(person, ["Hi", "."]); // Output: Hi, Alice.

Explanation: The apply method is particularly useful when arguments are already in an array format.

Try this: Copy the apply() function and test it in the code editor above to observe the output.

bind()

The bind method doesn’t immediately invoke the function. Instead, it creates a new function with the this value permanently set to the specified object.

const greetAlice = greet.bind(person);
greetAlice("Hey", "!"); // Output: Hey, Alice!

Explanation: This creates a new function greetAlice, where this is permanently set to the person object.

Try this: Copy the bind() function and test it in the code editor above to observe the output.

Arrow functions and this

Arrow functions do not have their own this. Instead, they take this from the surrounding context where they are defined.

const obj = {
name: "Charlie",
regularFunction: function() {
console.log(this.name); // `this` refers to the `obj` object
},
};
obj.regularFunction(); // Output: "Charlie"

Explanation: In this code, the regularFunction uses a traditional function, so this refers to the obj object, and thus this.name outputs "Charlie".

Key takeaways

  • The this keyword refers to an object, but the object it refers to depends on the context.

  • In a method, this refers to the object calling the method.

  • In the global context, this refers to the global object (like a window in browsers).

  • In strict mode, this inside a function is undefined.

  • Arrow functions do not have their own this; they inherit it from the outer scope.

Ready to learn JavaScript and build interactive web applications? Start our Learn JavaScript course and gain a solid foundation, preparing you for a career in web development. Ready to become a full-stack web developer? Begin our Become a Web Developer skill path, starting with the basics and advancing to expert-level skills, setting you up for success in web development.

1

What does the this keyword refer to when used in a global context in a browser environment?

A)

The object calling the function

B)

The window object

C)

The undefined value

Question 1 of 30 attempted

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the use of `this` keyword?

The this keyword is used in JavaScript to refer to the object it belongs to. It provides a way to access object properties or methods dynamically, depending on the context where it is used.


What is the `this` command in JavaScript?

The this command in JavaScript is a special keyword in the current execution context. In object methods, this refers to the object itself, while in functions or global code, its meaning can vary based on the mode (strict or default).


When do you use `this` in JavaScript?

You need to use this in JavaScript when you need to dynamically reference the object that is executing the current code. It’s commonly used in object methods, event handlers, and to share logic across multiple objects or functions.


Why is the `this` keyword forbidden in JavaScript?

The this keyword is not forbidden in JavaScript. However, its behavior can confuse beginners because its value changes depending on how and where a function is called. Arrow functions were introduced to simplify certain cases where this confuses by inheriting it from their surrounding context.


How do you ensure `this` always refers to the correct object?

Use arrow functions or methods like bind(), call(), or apply() to explicitly set the value of this.


Free Resources

Attributions:
  1. undefined by undefined