Sobes.tech
Middle

Tell about the context of functions in JavaScript.

sobes.tech AI

Answer from AI

The execution context (this) in JavaScript determines how a function is called and what values are accessible inside it. The context dynamically changes depending on the call method:

  • Global context: Outside functions, this refers to the global object (window in browsers, global in Node.js).
    // In a browser
    console.log(this === window); // true
    
    // In Node.js
    console.log(this === global); // true
    
  • Function context:
    • Standard call: In non-strict mode, this inside a function refers to the global object (if the function is not a method of an object). In strict mode ("use strict";), this will be undefined.
      function showThis() {
        console.log(this);
      }
      
      showThis(); // Non-strict: Global object; Strict: undefined
      
    • Called as an object method: this refers to the object that the method is a part of.
      const user = {
        name: 'Alice',
        greet: function() {
          console.log("Hello, my name is " + this.name);
        }
      };
      
      user.greet(); // Hello, my name is Alice
      
    • Called with new (constructor): Creates a new object, which becomes the value of this inside the constructor function, and returns that object.
      function Person(name) {
        this.name = name;
      }
      
      const person1 = new Person('Bob');
      console.log(person1.name); // Bob
      
    • Explicit context specification (call, apply, bind):
      • call(thisArg, arg1, arg2, ...): Calls the function with the specified this and arguments listed separately.
      • apply(thisArg, [argsArray]): Calls the function with the specified this and arguments as an array.
      • bind(thisArg, arg1, arg2, ...): Returns a new function with this permanently bound to thisArg and bound arguments.
      function introduce(greeting, punctuation) {
        console.log(greeting + ", I am " + this.name + punctuation);
      }
      
      const person = { name: 'Charlie' };
      
      introduce.call(person, "Hi", "!");  // Hi, I am Charlie!
      introduce.apply(person, ["Hello", "."]); // Hello, I am Charlie.
      
      const boundIntroduce = introduce.bind(person, "Hey");
      boundIntroduce("?"); // Hey, I am Charlie?
      
  • Arrow functions: Do not have their own this context. They capture this from the surrounding lexical scope (the scope in which they were defined).
    const obj = {
      name: 'David',
      sayLater: function() {
        // `this` here refers to obj
        setTimeout(() => {
          // `this` here also refers to obj (inherited from sayLater)
          console.log("Later, I am " + this.name);
        }, 1000);
      }
    };
    
    obj.sayLater(); // Later, I am David
    
Tell about the context of functions in JavaScript… - sobes.tech