Question 44

Question

Can you explain how JavaScript determines the value of this in nested functions?

Answer

this in nested functions is determined by several factors working together. It's all about lexical scoping and how execution context is set up.

Here's the breakdown:

  1. Lexical Scope: JavaScript looks for this value based on where the function was defined, not where it's called. This is why it's often said that this is determined by lexical scoping.

  2. Execution Context Stack: Each time a function is called, a new execution context is created and pushed onto a stack. The top of the stack determines the current context and therefore the value of this.

Scenario 1: Regular Function Calls

function outer() {
  const value = 'hello'; // This is part of the outer function's scope

  function inner() {
    console.log(this); // In this case, 'this' refers to the global object (window in browsers)
  }

  inner(); 
}

outer(); 

Explanation:

  • this inside inner() is bound to the global object because it's a regular function call.

Scenario 2: Nested Function Calls with Contextual Binding

const obj = {
  value: 'world', // Property of the object
  outer: function() {
    function inner() {
      console.log(this); // 'this' refers to the object (obj) itself
    }
    inner(); 
  }
};

obj.outer();

Explanation:

  • this inside inner() is bound to the object (obj) on which the outer method was called. This happens because of lexical scoping and how inner's context inherits from outer.

Key Points:

  • The lexical scope (where a function is defined) determines the initial binding of this.

  • However, contextual binding can override the default value of this, for example, with functions like call(), apply(), or bind().

Last updated