What is the difference between call, apply, and bind?
All three explicitly set this:
- call(thisArg, arg1, arg2) — invoke immediately, args individually
- apply(thisArg, [args]) — invoke immediately, args as array
- bind(thisArg, arg1) — returns new permanently-bound function
function greet(greeting, punct) {
return `${greeting}, ${this.name}${punct}`;
}
const user = { name: 'Priya' };
greet.call(user, 'Hello', '!'); // "Hello, Priya!"
greet.apply(user, ['Hi', '.']); // "Hi, Priya."
const fn = greet.bind(user, 'Hey');
fn('?'); // "Hey, Priya?"