Call, Apply and Bind
Every JavaScript function has three methods for controlling how it is called: call and apply call the function immediately with a chosen this value, and bind returns a new function whose this (and, optionally, first arguments) are fixed for good. They let one function work with any object, let you borrow methods from one type for another, and fix the "lost this" bug when passing methods as callbacks.
In One Minute
fn.call(thisArg, a, b)callsfnnow, withthis = thisArgand arguments listed.fn.apply(thisArg, [a, b])does the same, with arguments in an array.fn.bind(thisArg, a)returns a new function withthisand the first argument fixed; call it later.- Method borrowing:
Array.prototype.slice.call(arrayLike)uses an array method on something that isn't an array. - Modern code often uses spread (
fn(...args)) instead ofapply, and arrows instead ofbind.
Syntax
fn.call(thisArg, arg1, arg2, ...); // calls now
fn.apply(thisArg, [arg1, arg2, ...]); // calls now, arguments as an array
const bound = fn.bind(thisArg, arg1); // returns a new function
bound(arg2); // calls later: fn with this = thisArg, (arg1, arg2)| Method | Calls the function | Arguments | Returns |
|---|---|---|---|
call | Immediately | Listed one by one | The function's result |
apply | Immediately | One array (or array-like) | The function's result |
bind | No, returns a function | Optional, fixed in front | A new bound function |
A memory aid: apply takes an array; call takes commas.
call
function describe(currency, suffix) {
return `${this.name} owes ${this.balance} ${currency}${suffix}`;
}
const navika = { name: "Navika", balance: 120 };
const advitha = { name: "Advitha", balance: 45 };
console.log(describe.call(navika, "USD", "."));
console.log(describe.call(advitha, "USD", "!"));Navika owes 120 USD.
Advitha owes 45 USD!The function isn't a method of either object, yet call runs it as if it were.
apply
apply is the same, with the arguments in an array. It was essential before spread syntax existed, for passing an array of values to a function that takes separate arguments:
function describe(currency, suffix) {
return `${this.name} owes ${this.balance} ${currency}${suffix}`;
}
const args = ["USD", "?"];
console.log(describe.apply({ name: "Srihitha", balance: 85 }, args));
const fees = [120, 85, 450, 45];
console.log(Math.max.apply(null, fees));
console.log(Math.max(...fees));Srihitha owes 85 USD?
450
450Math.max.apply(null, fees) was the classic way to find an array's maximum; null is passed because Math.max doesn't use this. Spread syntax (Math.max(...fees)) does the same more readably, and is what modern code uses.
bind
bind doesn't call the function. It creates a bound function: calling it later always uses the bound this, no matter how it is called:
"use strict";
const account = {
owner: "Navika",
balance: 450,
pay(amount) {
this.balance -= amount;
return `${this.owner} has $${this.balance} left`;
},
};
const detached = account.pay;
try {
detached(100);
} catch (err) {
console.log("detached:", err.name);
}
const boundPay = account.pay.bind(account);
console.log(boundPay(100));
console.log([50, 25].map(boundPay));
const other = { owner: "Someone else", pay: boundPay };
console.log(other.pay(25));detached: TypeError
Navika has $350 left
['Navika has $300 left', 'Navika has $275 left']
Navika has $250 leftExplanation: the detached method has no this (strict mode), so reading this.balance throws. The bound version works when called directly, as a map callback, and even as a method of another object: its this is locked to account. A bound function can't be re-bound; calling bind on it again keeps the original this.
Removing Bound Listeners
Each call to bind creates a new function. To remove an event listener added with a bound function, keep a reference to that exact function:
class Clock {
constructor() {
this.onTick = this.tick.bind(this); // store the bound function once
}
start() { window.addEventListener("focus", this.onTick); }
stop() { window.removeEventListener("focus", this.onTick); } // same reference: works
tick() { /* uses this */ }
}
// removeEventListener("focus", this.tick.bind(this)) would remove nothing: it's a different function.Partial Application with bind
Arguments after thisArg are fixed in front. The bound function receives them first, followed by whatever it's called with:
function feeLine(currency, name, amount) {
return `${name}: ${amount} ${currency}`;
}
const usdLine = feeLine.bind(null, "USD");
console.log(usdLine("Navika", 120));
const navikaUsd = feeLine.bind(null, "USD", "Navika");
console.log([120, 60].map((amount) => navikaUsd(amount)));
console.log(usdLine.name, usdLine.length);Navika: 120 USD
['Navika: 120 USD', 'Navika: 60 USD']
bound feeLine 2Bound functions are named "bound " + original name, and their length is reduced by the number of fixed arguments, which is useful when debugging.
Method Borrowing
Many built-in methods work on any object that looks right, not just their own type. With call, you can use, for example, array methods on array-like objects (objects with length and numeric indexes), such as arguments or old DOM collections:
const arrayLike = { 0: "Navika", 1: "Srihitha", 2: "Advitha", length: 3 };
console.log(Array.prototype.join.call(arrayLike, " & "));
console.log(Array.prototype.map.call(arrayLike, (name) => name.toUpperCase()));
console.log(Array.from(arrayLike).filter((name) => name.startsWith("A")));
const toTag = (value) => Object.prototype.toString.call(value);
console.log(toTag([]), toTag(null), toTag(new Date(0)));
const record = { amount: 120, hasOwnProperty: () => "overridden!" };
console.log(Object.prototype.hasOwnProperty.call(record, "amount"), Object.hasOwn(record, "amount"));Navika & Srihitha & Advitha
['NAVIKA', 'SRIHITHA', 'ADVITHA']
['Advitha']
[object Array] [object Null] [object Date]
true trueExplanation: join and map only need length and numeric keys, so they work on the array-like object. Today, Array.from(arrayLike) is usually clearer. The last line shows another classic use: calling the original hasOwnProperty even when an object overrides it; Object.hasOwn (ES2022) is the modern replacement.
When You Don't Need Them
| Old pattern | Modern equivalent |
|---|---|
fn.apply(null, args) | fn(...args) |
Math.max.apply(null, arr) | Math.max(...arr) |
Array.prototype.slice.call(arguments) | [...arguments] or rest parameters |
this.handler = this.handler.bind(this) in a constructor | An arrow-function class field: handler = () => {...} |
setTimeout(this.tick.bind(this), 100) | setTimeout(() => this.tick(), 100) |
obj.hasOwnProperty.call(o, k) | Object.hasOwn(o, k) |
call remains useful for borrowing methods and for calling a parent's method in older inheritance code (Parent.call(this, ...), see the inheritance lesson).
In Practice
The Fee Tracker's legacy logger function uses this to know which module is logging. call reuses it for different modules, and bind creates permanent loggers for each:
function log(level, message) {
return `[${this.module}] ${level.toUpperCase()}: ${message}`;
}
console.log(log.call({ module: "payments" }, "info", "Recorded $120 for Navika"));
const reportLog = log.bind({ module: "reports" });
const reportError = log.bind({ module: "reports" }, "error");
console.log(reportLog("warn", "Grade 12 has no payments yet"));
console.log(reportError("Could not build the chart"));[payments] INFO: Recorded $120 for Navika
[reports] WARN: Grade 12 has no payments yet
[reports] ERROR: Could not build the chartCommon Mistakes
Expecting bind to call the function. It returns a new one; call that.
Removing a listener with a fresh bind. It's a different function, so nothing is removed. Store the bound function.
Using call, apply or bind on arrow functions to change this. Arrows ignore it (the arguments still pass through).
Using apply just to spread an array. Write fn(...args).
Interview Corner
What is the difference between call, apply and bind?
call and apply invoke the function immediately with a given this; call takes arguments individually and apply takes them as an array. bind returns a new function with this and optional leading arguments permanently fixed, to be called later. A bound function's this can't be changed again, except by new.
Implement bind.
A simplified version: Function.prototype.myBind = function (thisArg, ...fixed) { const fn = this; return function (...args) { return fn.apply(thisArg, [...fixed, ...args]); }; };. A complete version also handles new (using the new object instead of thisArg) and sets the prototype, name and length.
Implement a minimal bind and use it.
Show solution
Function.prototype.myBind = function (thisArg, ...fixed) {
const fn = this;
return function (...args) {
return fn.apply(thisArg, [...fixed, ...args]);
};
};
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const hello = greet.myBind({ name: "Srihitha" }, "Hello");
console.log(hello("!"));Hello, Srihitha!(Adding methods to built-in prototypes is fine for an exercise but should be avoided in real code.)
Practice
Challenge: Use Array.prototype.filter.call to get the even numbers from the array-like object { 0: 4, 1: 7, 2: 10, length: 3 }, then do the same with Array.from.
Show solution
const arrayLike = { 0: 4, 1: 7, 2: 10, length: 3 };
console.log(Array.prototype.filter.call(arrayLike, (n) => n % 2 === 0));
console.log(Array.from(arrayLike).filter((n) => n % 2 === 0));[4, 10]
[4, 10]Key Takeaways
| Need | Code |
|---|---|
Call with a this | fn.call(obj, a, b) |
| Call with an array of arguments | fn.apply(obj, args) or fn(...args) |
Fix this for later | const f = obj.method.bind(obj) |
| Fix leading arguments | fn.bind(null, "USD") |
| Borrow an array method | Array.prototype.map.call(arrayLike, fn) |
Was this tutorial helpful?