Sobes.tech
Junior — Middle

How can you change the current execution context (this) inside a JavaScript function?

sobes.tech AI

Answer from AI

In JavaScript, you can change the execution context (this value) inside a function using the following methods:

  1. Methods call and apply — invoke a function with a specified context.
function greet() {
  console.log(this.name);
}

const user = { name: 'Ivan' };
greet.call(user);  // Ivan
  1. Method bind — returns a new function with a bound context.
const boundGreet = greet.bind(user);
boundGreet();  // Ivan
  1. Using arrow functions — arrow functions do not have their own this; they inherit the context from the outer scope.
const obj = {
  name: 'Anna',
  greet: function() {
    const arrow = () => console.log(this.name);
    arrow();
  }
};
obj.greet();  // Anna
  1. Direct call through an object — when calling obj.method(), this inside the method refers to obj.

  2. Using a variable to save the context (e.g., const self = this;) — an outdated method; nowadays, arrow functions are preferred.

These methods allow you to control what this refers to inside a function.