Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 156 ยท Functions

call, apply and bind

Use call(), apply() and bind() to choose this for a JavaScript function, borrow methods, fix lost this in callbacks and pre-fill arguments.

In the previous lesson you saw that a regular function's this depends on how it is called. Usually that means "the object before the dot". But sometimes you want to decide this yourself: to reuse a function with a different object, to borrow a method from somewhere else, or to make sure a callback keeps its object no matter who calls it.

Every function in JavaScript has three methods for that: call(), apply() and bind(). The first two call the function immediately with a this you choose. The third returns a new function with this locked in place โ€” and, as a bonus, can pre-fill some arguments too.

call(): call with a chosen this

fn.call(thisArg, arg1, arg2, โ€ฆ) calls fn right away. Inside it, this is thisArg, and the remaining arguments are passed along as normal:

JS call() picks this for one call

Press Run (or Ctrl + Enter) to see the console output here.

No output.

cow doesn't have a speak method, but call() lets it borrow cat's. The function doesn't belong to any object; this is just a hidden parameter that call() lets you fill in.

apply(): arguments as an array

apply() does exactly the same as call(), except that it takes the arguments as one array (or array-like object) instead of a list:

JavaScript
introduce.call(ada, "Hi", "!");
introduce.apply(ada, ["Hi", "!"]);   // same result

A memory aid: apply takes an array, call takes commas.

Before spread syntax existed, apply() was the standard way to pass an array of values to a function that expects separate arguments. You will still meet it in older code:

JS apply() and its modern replacement

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When this doesn't matter, as with Math.max, the first argument is conventionally null. Today you'll rarely need apply() โ€” spread does the job more readably โ€” but you should recognize it.

What happens with null or a primitive

The value you pass as thisArg is used as-is in strict code. In sloppy code, JavaScript adjusts it: null and undefined are replaced by the global object, and primitives like 5 or "hi" are wrapped in objects.

JS thisArg in sloppy vs strict functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is one more reason modules and classes, which are always strict, are less surprising.

bind(): lock this for later

call() and apply() run the function now. bind() doesn't run anything. It returns a new function that, whenever it is called, calls the original with this fixed to the value you chose:

JavaScript
const boundIntroduce = introduce.bind(ada);
boundIntroduce("Hey", "?"); // "Hey, I'm Ada?"

That is exactly what you need when you hand a method to code that will call it later โ€” timers, event listeners, array methods โ€” because those callers would otherwise call it as a plain function and lose this:

JS Fixing a lost this with bind()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Bound means bound for good. Once a function is bound, its this can't be changed again: bound.call(other) and a second bind() are both ignored for this. The one exception is new, which still creates a fresh object. Arrow functions ignore the thisArg of call, apply and bind entirely, because they have no this of their own.

Removing bound listeners

Each call to bind() returns a different function. That matters for removeEventListener(), which only removes the exact function that was added:

JavaScript
button.addEventListener("click", menu.toggle.bind(menu));
button.removeEventListener("click", menu.toggle.bind(menu)); // does nothing!

// Keep a reference instead:
const onClick = menu.toggle.bind(menu);
button.addEventListener("click", onClick);
button.removeEventListener("click", onClick); // works

bind() or an arrow?

Wrapping the call in an arrow โ€” setTimeout(() => watch.tick(), 200) โ€” solves the same problem and is often easier to read, especially when you need to pass arguments. bind() is handy when you want to store or pass a ready-made function, and in classes some developers bind methods in the constructor (this.tick = this.tick.bind(this);) or use arrow class fields. All of these are valid; choose one style per project.

Partial application with bind()

bind() accepts extra arguments after thisArg. They are pre-filled at the front of the argument list every time the bound function is called. Creating a more specific function by fixing some of the arguments of a general one is called partial application:

JS Pre-filling arguments with bind()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same can be written with a closure โ€” const warn = (...m) => log("WARN", ...m); โ€” and many developers prefer that because it works the same for arrows and doesn't involve this at all. bind() is just the built-in shortcut.

Borrowing methods

call() lets you run a method from one type on a value of another type, as long as the value has what the method needs. The classic case is an array-like object: something with numbered keys and a length, but none of the array methods. arguments, NodeLists from older APIs and strings are all array-like.

JavaScript
const arrayLike = { 0: "red", 1: "green", 2: "blue", length: 3 };

Array.prototype.join.call(arrayLike, " / ");       // "red / green / blue"
Array.prototype.map.call("abc", (ch) => ch.toUpperCase()); // ["A", "B", "C"]

Modern code usually converts first with Array.from(arrayLike) or [...iterable] and then uses normal array methods, which reads better. Still, you'll see Array.prototype.slice.call(arguments) in older libraries, and now you know what it does.

Which one should you use?

  • You want to run the function now with a specific this: use call(). It's the most readable of the two immediate options.
  • Your arguments are already in an array: spread them into call() or a normal call; reach for apply() mainly when reading or maintaining older code.
  • You need a function to hand to someone else (a timer, a listener, an array method) and it must keep its object: use bind(), or wrap the call in an arrow.
  • You want a specialized version of a general function: partial application with bind(), or a small closure.
  • Your function doesn't use this at all: none of these are needed for this; just call it normally.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between call() and apply()?

    Both call the function immediately with the chosen this. They differ only in how the remaining arguments are passed.
  2. 2. What does fn.bind(obj) do?

    bind() doesn't run the function. It returns a bound copy you can call later, as often as you like.
  3. 3. Given const f = greet.bind(a); f.call(b);, which object is this inside greet?

    A bound function's this can't be changed by call, apply or another bind.
  4. 4. function add(a, b) { return a + b; } โ€” what does add.bind(null, 10)(5) return?

    The bound function pre-fills a with 10, and the 5 you pass becomes b.
  5. 5. Why does removeEventListener("click", obj.handle.bind(obj)) fail to remove a listener added the same way?

    Only the identical function reference can be removed. Store the bound function in a variable and use it in both calls.

Summary

  • fn.call(thisArg, a, b) calls fn now with the chosen this and separate arguments.
  • fn.apply(thisArg, [a, b]) does the same with an array of arguments; spread syntax has mostly replaced it.
  • fn.bind(thisArg) returns a new function with this permanently fixed โ€” the standard fix for methods used as callbacks.
  • Extra arguments to bind() are pre-filled: that's partial application.
  • In sloppy code, a null or undefined thisArg becomes the global object; strict code keeps it as is. Arrow functions ignore thisArg entirely.

Next: Functional Programming Patterns.