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:
- Methods
callandapply— invoke a function with a specified context.
function greet() {
console.log(this.name);
}
const user = { name: 'Ivan' };
greet.call(user); // Ivan
- Method
bind— returns a new function with a bound context.
const boundGreet = greet.bind(user);
boundGreet(); // Ivan
- 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
-
Direct call through an object — when calling
obj.method(),thisinside the method refers toobj. -
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.