JavaScript call, apply, and bind
The call, apply, and bind methods run a function with a chosen this. Call and apply run at once, and bind saves the choice for later.
Borrow a method with call
The greet method belongs to greeter. Call runs it at once with this set to the other object.
const greeter = {
greet: function () {
console.log("Hello, " + this.name);
}
};
const other = { name: "Ben" };
greeter.greet.call(other);Pass arguments with apply
Apply takes the arguments as one array. The function still runs at once, with this set to the box object.
function add(a, b) {
console.log(this.base + a + b);
}
const box = { base: 10 };
add.apply(box, [1, 2]);Fix this with bind
The loose copy runs with no object, so it reads undefined. The bound copy keeps the counter, so it reads 5.
const counter = {
count: 5,
read: function () {
console.log(this.count);
}
};
const loose = counter.read;
loose();
const readIt = counter.read.bind(counter);
readIt();Example
function introduce(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
const person = { name: "Ana" };
introduce.call(person, "Hello", "!");
introduce.apply(person, ["Hi", "?"]);
const bound = introduce.bind(person, "Hey");
bound("...");Key points
- call: a method that runs a function now with a chosen this
- apply: a method that runs a function now, taking its arguments as an array
- bind: a method that makes a new function with this fixed
- Use call or apply to borrow a method for another object.
- A bound function keeps its this no matter how it is called later.
In this example, call passes each argument on its own, and apply passes them as one array. Bind fixes both the object and the first argument, so the later call only supplies the last one.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does greet.call(other) do?