This Keyword

priyanka kumaripriyanka kumari
6 min read

What is this in JavaScript? (Definition & Importance)

The this keyword in JavaScript is a special identifier that refers to the object that is currently executing the function or code in which it appears. Its value is determined by how a function is called, not where it is defined. This dynamic nature makes this both powerful and sometimes confusing. It enables context-aware operations, access to object properties and methods, and is fundamental to object-oriented and event-driven programming in JavaScript234.

Importance of this:

  • Provides dynamic context for function execution.

  • Facilitates object-oriented code by allowing methods to reference their own object.

  • Enables event handling by referring to DOM elements in event listeners.

  • Essential for constructors and class-based patterns34.

Global Context (this in the Global Scope)

  • In the global scope (outside any function or object), this refers to the global object:

    • In browsers: window

    • In Node.js: global

  • Example:

      jsconsole.log(this); // window (in browser)
    
  • Assigning properties to this in the global scope attaches them to the global object28.

this in Strict Mode ('use strict')

  • In strict mode, this in global or standalone function context is undefined, not the global object.

  • Example:

      js'use strict';
      function show() {
        console.log(this); // undefined
      }
      show();
    
  • This prevents accidental modifications to the global object26.

Function Context & this

this in Regular Functions

  • When a regular function is called in the global context, this refers to the global object (or undefined in strict mode).

  • When called as a method of an object, this refers to the object owning the method27.

this in Arrow Functions (Lexical this)

  • Arrow functions do not have their own this. Instead, they inherit this from their surrounding (lexical) scope.

  • Useful for preserving context in callbacks and nested functions4.

  • Example:

      jsconst obj = {
        value: 10,
        method: function() {
          setTimeout(() => {
            console.log(this.value); // 10
          }, 100);
        }
      };
      obj.method();
    

this in Object Methods

  • When a function is called as a method of an object, this refers to that object.

  • Example:

      jsconst user = {
        name: "Alice",
        greet: function() {
          console.log(this.name); // "Alice"
        }
      };
      user.greet();
    

this in Constructor Functions (new keyword)

  • When a function is called with new, this refers to the newly created instance.

  • Example:

      jsfunction Person(name) {
        this.name = name;
      }
      const p = new Person("Bob");
      console.log(p.name); // "Bob"
    

Dynamic Binding of this

Explicit Binding (call, apply, bind)

  • You can explicitly set the value of this for any function using call, apply, or bind.

  • Example:

      jsfunction show() { console.log(this.name); }
      const user = { name: "Carol" };
      show.call(user); // "Carol"
    
  • bind returns a new function with permanently bound this5.

Implicit Binding (Object Property Call)

  • When a function is called as a property of an object, this is set to that object.

  • Example:

      jsobj.method();
    

Default Binding

  • If none of the above rules apply, this defaults to the global object (or undefined in strict mode)36.

Lost Binding

  • Assigning a method to a variable or passing it as a callback can cause this to lose its intended context (becoming global or undefined).

  • Example:

      jsconst greet = user.greet;
      greet(); // `this` is global or undefined
    

Advanced Concepts

this inside Event Listeners

  • In regular functions, this refers to the DOM element that received the event.

  • In arrow functions, this is inherited from the outer scope (often not the element)4.

Arrow Functions vs Regular Functions in Callbacks

  • Arrow functions inherit this from the parent scope.

  • Regular functions assign this based on how they are called.

this inside Classes & Class Methods

  • In ES6 classes, this inside methods refers to the instance of the class.

  • Arrow functions as class properties can help preserve this in callbacks.

this inside setTimeout & setInterval

  • Regular functions: this defaults to global or undefined.

  • Arrow functions: this is inherited from the enclosing scope4.

this inside Promises, Async/Await

  • Inside promise callbacks or async functions, this follows the same rules as regular or arrow functions.

this in Array Methods (map, forEach, filter, etc.)

  • Regular functions: this is global or undefined unless explicitly bound.

  • Arrow functions: this is inherited from the parent scope.

this in ES6 Modules vs CommonJS Modules

  • In ES6 modules, top-level this is undefined.

  • In CommonJS (Node.js), top-level this is module.exports.

Practical Applications

Handling this in React Components

  • Class Components: this refers to the component instance; methods often need to be bound in the constructor or defined as arrow functions.

  • Functional Components: No this; use hooks for state and lifecycle.

How this works in Event Delegation

  • In event delegation, this refers to the element that triggered the event, allowing generic handlers.

Fixing this Issues in JavaScript Code

  • Use arrow functions to preserve the outer this.

  • Use bind, call, or apply to explicitly set this.

  • Store reference to this in a variable (const self = this) in older code.

Summary Table: this Behavior in Different Contexts

ContextValue of this
Global scopeGlobal object (window/global)
Function (non-strict)Global object
Function (strict mode)undefined
Object methodThe object
Constructor (new)New instance
Arrow functionLexically inherited from parent scope
Event listener (regular function)Event target (DOM element)
Event listener (arrow function)Lexically inherited from parent scope
call/apply/bindExplicitly set by the method

Tasks

Using "this" in object literal

importance: 5

Here the function makeUser returns an object.

What is the result of accessing its ref? Why?

function makeUser() {
  return {
    name: "John",
    ref: this
  };
}

let user = makeUser();

alert( user.ref.name );

Create a calculator

importance: 5

Create an object calculator with three methods:

let calculator = {
  // ... your code ...
};

calculator.read();
alert( calculator.sum() );
alert( calculator.mul() );

Chaining

importance: 2

There’s a ladder object that allows you to go up and down:

let ladder = {
  step: 0,
  up() {
    this.step++;
  },
  down() {
    this.step--;
  },
  showStep: function() { 
    alert( this.step );
  }
};

Now, if we need to make several calls in sequence, we can do it like this:

ladder.up();
ladder.up();
ladder.down();
ladder.showStep(); // 1
ladder.down();
ladder.showStep(); // 0

Modify the code of up, down, and showStep to make the calls chainable, like this:

ladder.up().up().down().showStep().down().showStep();
0
Subscribe to my newsletter

Read articles from priyanka kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

priyanka kumari
priyanka kumari