call(), apply(), bind()
MediumIn plain terms
call and apply invoke a function with a specific this and arguments. call takes args individually; apply takes an array. bind returns a new function with this and optional args pre-set.
What you need to know
- •call(thisArg, ...args)
- •apply(thisArg, [args])
- •bind(thisArg, ...args) returns function
Try it yourself
Copy the code below and run it in your browser console or a code editor:
function greet(greeting, punctuation) {
return greeting + ', ' + this.name + punctuation;
}
const person = { name: 'Alice' };
greet.call(person, 'Hello', '!'); // "Hello, Alice!"
greet.apply(person, ['Hi', '.']); // "Hi, Alice."
const boundGreet = greet.bind(person, 'Hey');
boundGreet('!'); // "Hey, Alice!"
// bind for event handlers
this.handleClick = this.handleClick.bind(this);Learn more
Dive deeper with these trusted resources: