Skip to main content

Command Palette

Search for a command to run...

Understanding `this` Keyword in JavaScript

Importance of `this`

Updated
•4 min read•View as Markdown
Understanding `this` Keyword in JavaScript
S
Software Developer | Full Stack Developer |

What this Keyword in JavaScript represents?

The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run. Most typically, it is used in object methods, where this refers to the object that the method is attached to, thus allowing the same method to be reused on different objects.

In JavaScript, the this keyword refers to the object that is currently executing or calling the function. Its value is determined dynamically at runtime based on how the function is invoked, rather than where it is defined.

this in Global Context:

In JavaScript, the this keyword in the global context (outside of any function) refers to the global object. In a browser environment, this global object is the window object. In Node.js, it is the global object, though within a module's top-level code, this is equivalent to module.exports rather than the global object itself.

// In Node.js environment
console.log(this) // Output: {} (Empty Object)

this inside Objects:

In JavaScript, the this keyword inside an object method refers to the object that the method is called on (the object "before the dot"). This binding is determined at run-time, meaning the same function can have different this values depending on how it is invoked. For example, if user.greet() is called, this inside greet refers to the user object, allowing access to its properties like this.name.

const user = {
  name: "Alice",
  age: 45,
  greet: function () {
    return `My name is \({this.name} and age is \){this.age}`;
  },
};

console.log(user.greet()); // Output: My name is Alice and age is 45.

this inside Functions:

In JavaScript, the value of this inside a regular function is determined by how the function is called (runtime binding), not how it is defined. If a function is called as a method of an object (e.g., obj.method()), this refers to that object. If called as a standalone function (e.g., func()), this refers to the global object (globalThis) in non-strict mode, or undefined in strict mode.

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

test(); // undefined

How calling context changes this:

In JavaScript, the value of the this keyword is not determined by where a function is defined, but by how it is called. It dynamically refers to the execution context or the object that invokes the function at runtime.

Default Binding Rules

  • Global Context: When a function is called independently (not as a method), this refers to the global object (window in browsers, global in Node.js). In strict mode, this is undefined instead.

  • Method Invocation: When a function is called as a property of an object (e.g., obj.method()), this refers to the object preceding the dot.

  • Constructor Invocation: When a function is called with the new keyword, this is bound to the newly created instance object.

Explicit Context Changes

You can manually override the default binding using built-in methods:

  • call() and apply(): These invoke the function immediately with this set to the first argument provided. The difference is that call() takes individual arguments, while apply() takes an array of arguments.

  • bind(): This creates a new function with this permanently bound to the specified object, which is useful for preserving context in callbacks or event listeners.

Arrow Functions and Lexical Scoping

Arrow functions (() => {}) do not have their own this context. Instead, they inherit this from the enclosing lexical scope where they were defined. This behavior cannot be changed using call(), apply(), or bind(), making arrow functions ideal for nested functions where preserving the outer context is desired.

Common Pitfalls

  • Nested Functions: Regular inner functions lose the parent object's context and default to the global object (or undefined in strict mode). Using arrow functions or binding this resolves this.

  • Callbacks: When passing a method as a callback (e.g., to setTimeout or event listeners), the function loses its object context. Explicit binding via .bind(this) or using arrow functions is required to maintain access to the object's properties.

Conclusion:

  • Functions that are stored in object properties are called “methods”.

  • Methods allow objects to “act” like object.doSomething().

  • Methods can reference the object as this.

The value of this is defined at run-time.

  • When a function is declared, it may use this, but that this has no value until the function is called.

  • A function can be copied between objects.

  • When a function is called in the “method” syntax: object.method(), the value of this during the call is object.

Please note that arrow functions are special: they have no this. When this is accessed inside an arrow function, it is taken from outside.