Skip to content

Latest commit

 

History

History
155 lines (112 loc) · 3.51 KB

File metadata and controls

155 lines (112 loc) · 3.51 KB

This Keyword in JavaScript

What is this in JavaScript?

  • this is a special keyword that refers to the execution context — the object that is currently calling or owning the code.
  • Its value depends on how the function is called, not where it's written.
  • this is dynamic (changes with call style), except in arrow functions (lexical binding).

this in Different Contexts

a) Global Context

console.log(this);
// In browsers → window
// In Node (ESM) → undefined
  • In non-strict mode: this is the global object (window in browsers).
  • In strict mode: this is undefined.

b) Inside a Function

function showThis() {
  console.log(this);
}
showThis(); // global object (non-strict) OR undefined (strict)

c) Inside an Object Method

const obj = {
  name: 'John',
  greet() {
    console.log(this.name);
  },
};
obj.greet(); // "John"

Here, this refers to the object before the dot.

d) In a Constructor Function / Class

function Person(name) {
  this.name = name;
}
const p = new Person('Alice');
console.log(p.name); // "Alice"

With new, this refers to the newly created object.

e) Arrow Functions

const obj = {
  value: 42,
  arrow: () => console.log(this.value),
};
obj.arrow(); // undefined
  • Arrow functions do not have their own this.
  • They inherit this from the lexical scope where they were defined.

f) Event Handlers

document.querySelector('button').addEventListener('click', function () {
  console.log(this); // The button element
});

In a DOM event handler, this refers to the element that received the event (unless using an arrow function).

g) Explicit Binding (call, apply, bind)

function greet(city) {
  console.log(`Hello ${this.name} from ${city}`);
}

const user = { name: 'Bob' };

greet.call(user, 'Paris'); // Hello Bob from Paris
greet.apply(user, ['London']); // Hello Bob from London
const boundGreet = greet.bind(user, 'Rome');
boundGreet(); // Hello Bob from Rome
  • call → invoke immediately, pass arguments individually.
  • apply → invoke immediately, pass arguments as array.
  • bind → returns a new function with bound this.

Common Pitfalls

❌ Losing this in callbacks:

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

Fix: Use arrow functions or .bind(this):

setTimeout(() => console.log(this.name), 1000);

❌ Assuming this is always the object — it depends on call style, not location.

❌ Arrow functions as object methods — they don't have their own this.

this Binding Priority

When multiple rules apply, priority order:

  1. new binding (constructor) → highest priority
  2. Explicit binding (call, apply, bind)
  3. Implicit binding (object method call)
  4. Default binding (global object or undefined in strict mode)
  5. Arrow functions → ignore all above, use lexical scope

Sample Interview Questions

  1. What does this refer to in the global scope in strict mode vs non-strict mode?

  2. How does this behave inside arrow functions vs normal functions?

  3. What's the output of:

    const obj = {
      a: 10,
      b: () => console.log(this.a),
    };
    obj.b();
  4. How do call, apply, and bind affect this?

  5. What happens to this when you extract a method from an object and call it standalone?

  6. How does this work in event handlers?