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
call
andapply
to invoke functions with a specificthis
. - Use
bind
to create a new function with presetthis
and/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/apply
this
because theirthis
is lexical. bind
returns a new function; remember to call it.