JavaScript - call, apply, bind
Overview
Estimated time: 20–30 minutes
Set the this context and pass arguments explicitly using call, apply, and bind.
Learning Objectives
- Use
callandapplyto invoke functions with a specificthis. - Use
bindto create a new function with presetthisand/or arguments.
Prerequisites
Examples
function greet(greeting) {
return `${greeting}, ${this.name}`;
}
const user = { name: 'Ada' };
greet.call(user, 'Hello'); // 'Hello, Ada'
greet.apply(user, ['Hi']); // 'Hi, Ada'
const hi = greet.bind(user, 'Hi');
hi(); // 'Hi, Ada'
Common Pitfalls
- Arrow functions ignore
call/applythisbecause theirthisis lexical. bindreturns a new function; remember to call it.