'this' Keyword in JavaScript​: A Quick, Simple Guide

'this' Keyword in JavaScript: A Quick, Simple Guide


In JavaScript, this is a special keyword that refers to the ‘owner’ of the current execution context—often the object or scope where your function is running. But if you’ve ever observed, you might have noticed that `this` doesn’t always point to the same thing. Don’t worry—you’re not alone in finding that confusing! Let’s walk through it step by step with simple examples.


1. Global Scope

  • Outside of any function or class, this points to the global object (in browsers, that’s window).
  • This happens regardless of whether you’re in strict mode or not.

// In a browser's console:
console.log(this); // Points to window        

2. Inside Regular Functions

Non-Strict Mode

  • Calling a function directly (e.g. fn()) sets this to window.

Strict Mode

  • this becomes undefined if the function is called without an owner (e.g. fn()).

Note: “In non-strict mode, JavaScript uses a feature called ‘this substitution.’ This means if this refers to null or undefined, it will automatically set to the global object (usually window).”
function fn() {
  console.log(this);
}

// Non-strict: window,  Strict: undefined
fn();  

// always window (calling through window explicitly)
window.fn();           


3. Binding a Function’s this

we can enforce a function to use a specific this value by using bind, call, or apply. The first argument you provide to these methods becomes this, inside the function.

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

let obj = { 'a': 1 };

let boundFn = showThis.bind(obj);
boundFn(); // { a: 1 }

let boundToNull = showThis.bind(null);

// window in non-strict mode, undefined in strict mode
boundToNull(); 
        

4. Object Methods

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

let person = {
  firstName: "Tony",
  lastName:  "Stark",

  getFullName: function() {
    console.log(this.firstName + " " + this.lastName);
  }
};

person.getFullName();  // "Tony Stark" (this = person)
        

You can also “borrow” a method using call or apply:

let anotherObj = { firstName: "Peter", lastName: "Parker" };

// "Peter Parker" (this = anotherObj)
person.getFullName.call(anotherObj);         
“Borrowing a method” means using a function from one object on a different object, without copying the whole function. How? By passing the new object as the first argument to call or apply. This makes this refer to that new object.

5. Arrow Functions

  • Arrow functions don’t have their own this. Instead, they inherit the this from the lexical (parent) scope.
  • Even if you use call or apply or bind, it won’t change the arrow function’s this.

// Global arrow function
let arrowFn = () => {
// Points to window if defined in global scope
  console.log(this); 
};

arrowFn(); // window
arrowFn.call(person); // Still window

// Arrow function inside an object
let employee = {
  role: "Developer",
  
  arrowMethod: () => {
    // Still window, because it inherits from global scope
    console.log(this); 
  },

  regularMethod: function() {
    console.log(this); // this = employee

    let nestedArrow = () => {
      // this still = employee, inherited from regularMethod
      console.log(this); 
    };
    nestedArrow();
  }
};

employee.arrowMethod(); // window

// Logs employee object, then employee object again
employee.regularMethod();         

6. Callbacks and Promises

  • A callback function is called with a this value of undefined.
  • When you pass a regular function (non-arrow functions) as a callback, if it’s not bounded to any object, this often ends up undefined (in strict mode) or window (in non-strict mode).
  • In promise .then() chains, it depends on how you declare the function (regular vs. arrow).

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

function triggerCallback(cb) {
  cb(); 
}

// non-strict: window, strict: undefined
triggerCallback(callbackFn);   

let p = new Promise((resolve) => { resolve('done'); });

p
.then(function(res) {
  "use strict";
  // undefined (strict mode in a regular function)
  console.log(this); 
})
.then(function(res) {
  // window (non-strict mode)
  console.log(this); 
})
.then((res) => {
   // Inherits from parent scope (often global scope in many contexts)
  console.log(this); 
});
        

In Short

  1. Global scope: this = global object (window).
  2. Regular function (non-strict): this = global object (window).
  3. Regular function (strict): this = undefined.
  4. Object method: this = the object that owns the method.
  5. Arrow functions: don't have own this; it’s inherited from the parent scope.
  6. Bind/Call/Apply: forcibly set or change this.
  7. Callbacks: called with undefined, if not attached to an object.


I hope this helps you grasp how this works in JavaScript. Whenever you see this, ask yourself: “How was this function called, and under what context?” That single question usually unravels the mystery of the this keyword.

Feel free to reach out if you have any questions or additional insights—sharing is how we all learn better!

To view or add a comment, sign in

Others also viewed

Explore content categories