Three ways to explicitly control what this refers to inside a function.
- call(thisArg, a, b, ...) — invokes immediately, arguments listed individually
- apply(thisArg, [a, b, ...]) — invokes immediately, arguments as an array
- bind(thisArg, a, b, ...) — returns a NEW function with this permanently bound
function greet(greeting) {
return `${greeting}, ${this.name}`;
}
const user = { name: 'Grace' };
greet.call(user, 'Hi'); // 'Hi, Grace'
greet.apply(user, ['Hello']); // 'Hello, Grace'
const bound = greet.bind(user);
bound('Hey'); // 'Hey, Grace'