Function call()
Function.prototype.call(thisArg, …args) invokes a function with an explicit this and arguments passed individually.
Basics
JS
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const user = { name: "Ada" };
greet.call(user, "Hi", "!"); // "Hi, Ada!"
Borrowing methods from other types
JS
// Convert array-like to array (legacy way)
function legacy() {
const args = Array.prototype.slice.call(arguments);
// args is a real array
}
// Modern way
function modern(...args) { /* args is already an array */ }
// Use Array methods on a NodeList
const buttons = document.querySelectorAll("button");
Array.prototype.forEach.call(buttons, b => b.disabled = true);
// or just: [...buttons].forEach(…)
call vs apply vs bind
| Method | How args are passed | Returns |
|---|---|---|
call | One by one | The function's result (called immediately) |
apply | As an array | The function's result (called immediately) |
bind | One by one | A NEW function that remembers this and any args |
Tip: Most "borrow a method" patterns are now obsolete thanks to spread and rest. Reach for
call only when you actually need to swap this on the fly.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Function call()!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Invoke greet with `user` as `this` and two args using call().
greet.
(user, 'Hi', '!');
Four letters.
Discussion
Loading…