iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

MethodHow args are passedReturns
callOne by oneThe function's result (called immediately)
applyAs an arrayThe function's result (called immediately)
bindOne by oneA 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', '!');

Test yourself

Q1. `fn.call(obj, a, b)` differs from `fn.apply(obj, [a, b])` because…
Q2. Modern replacement for `Math.max.apply(null, arr)` is…
Q3. Inside a strict-mode function, passing `null` as the call thisArg makes `this`…

Discussion

Loading…