Sub topic 6
Setting this with call and apply
The previous chapter showed how methods lose their this when you pull them off an object or pass them as callbacks. This chapter covers the most direct fix: telling the function exactly what this should be when you call it. Every regular function inherits two methods from Function.prototype for this, call and apply. This is called explicit binding.
This chapter assumes you know how default binding works in sloppy and strict mode, how implicit binding works through method calls, and how this gets lost when a method is extracted. You should also be comfortable with rest and spread syntax and with array-like objects such as arguments.
The Two Signatures
Both methods invoke the function immediately. The first argument becomes this. The only difference is how the remaining arguments are passed:
| Method | Signature | Arguments passed as |
|---|---|---|
| `call` | `fn.call(thisArg, arg1, arg2, ...)` | A comma-separated list |
| `apply` | `fn.apply(thisArg, argsArray)` | One array or array-like object |
A common memory aid: apply takes an array, call takes commas.
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const ada = { name: 'Ada' };
const grace = { name: 'Grace' };
console.log(greet.call(ada, 'Hello', '!')); // 'Hello, Ada!'
console.log(greet.apply(ada, ['Hi', '?'])); // 'Hi, Ada?'
console.log(greet.call(grace, 'Welcome', '.')); // 'Welcome, Grace.'The same greet function runs against different objects without being attached to either of them. Neither ada nor grace has a greet property. The call site alone decides this, and call and apply let you write that decision out explicitly.
Fixing a Lost Binding at the Call Site
Recall the extracted method problem. Once increment is stored in a variable, a plain call gives it no this. With call, you supply the object again:
'use strict';
const counter = {
count: 0,
increment(step = 1) {
this.count += step;
return this.count;
}
};
const inc = counter.increment;
// inc(); // TypeError: this is undefined
console.log(inc.call(counter)); // 1
console.log(inc.call(counter, 5)); // 6
console.log(inc.apply(counter, [2])); // 8This fix only applies to the one call you make. call and apply do not change the function, and the next plain inc() still throws. If you need to hand the function to code you do not control, such as a timer or an event system, you cannot put call at that call site. The next chapter's bind handles that case.
How thisArg Is Treated: Strict vs Sloppy
What this actually ends up as depends on whether the called function is strict. The mode of the code doing the calling does not matter.
In strict functions, thisArg is passed through exactly as given. In sloppy functions, the engine applies two conversions:
- If
thisArgisnullorundefined,thisbecomesglobalThis. - If
thisArgis a primitive (number, string, boolean, symbol, bigint), it is boxed into its wrapper object.
// Run as a classic script or a CommonJS file (not an ES module).
function sloppyThis() {
return this;
}
function strictThis() {
'use strict';
return this;
}
console.log(sloppyThis.call(null) === globalThis); // true
console.log(sloppyThis.call(undefined) === globalThis); // true
console.log(typeof sloppyThis.call(42)); // 'object' (a Number wrapper)
console.log(strictThis.call(null)); // null
console.log(strictThis.call(undefined)); // undefined
console.log(typeof strictThis.call(42)); // 'number'The boxing rule also explains a subtle bug: in sloppy mode, this === 42 is always false inside a function called with call(42), because this is a Number object, not the primitive. Comparisons with === fail. You need this.valueOf() or strict mode to get the raw value.
Borrowing Methods
Explicit binding lets you run a method from one object's prototype against a different object that was never meant to have it. This is called method borrowing, and it works whenever the borrowed method only relies on the properties it reads from this.
Array methods on array-likes
Most Array.prototype methods are deliberately generic. They read this.length and indexed properties, so any array-like object works:
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const upper = Array.prototype.map.call(arrayLike, (s) => s.toUpperCase());
console.log(upper); // ['A', 'B', 'C']
console.log(Array.prototype.join.call(arrayLike, '-')); // 'a-b-c'
function legacyArgs() {
// arguments is array-like but has no array methods
return Array.prototype.slice.call(arguments, 1);
}
console.log(legacyArgs(1, 2, 3)); // [2, 3]In modern code, Array.from(arrayLike) and rest parameters (...args) usually replace these patterns. You will still see Array.prototype.slice.call(arguments) in older libraries, and it is worth recognizing.
Safe property checks
Objects created with Object.create(null) have no prototype, so they lack hasOwnProperty. An object can also shadow hasOwnProperty with its own property. Borrowing the method from Object.prototype avoids both problems:
const dict = Object.create(null);
dict.key = 1;
console.log(typeof dict.hasOwnProperty); // 'undefined'
console.log(Object.prototype.hasOwnProperty.call(dict, 'key')); // true
const tricky = { hasOwnProperty: () => false, real: 1 };
console.log(tricky.hasOwnProperty('real')); // false (wrong)
console.log(Object.prototype.hasOwnProperty.call(tricky, 'real')); // true
// ES2022 and later provide a static shortcut:
console.log(Object.hasOwn(tricky, 'real')); // trueReliable type tags
Object.prototype.toString reports an internal tag when called with call, which is more precise than typeof:
const tag = (value) => Object.prototype.toString.call(value);
console.log(tag([])); // '[object Array]'
console.log(tag(null)); // '[object Null]'
console.log(tag(new Date())); // '[object Date]'Constructor Chaining Without class
Before class and super, the usual way to reuse a parent constructor's setup was to call it with the new instance as this:
function Animal(name) {
this.name = name;
}
function Dog(name, breed) {
Animal.call(this, name); // run Animal's setup on the Dog instance
this.breed = breed;
}
const rex = new Dog('Rex', 'Collie');
console.log(rex.name, rex.breed); // 'Rex' 'Collie'Inside Dog, this is the fresh object that new created. Animal.call(this, name) runs Animal against that same object. The new chapter explains where that object comes from. This pattern does not work with ES2015 classes as the parent, because class constructors throw if invoked without new.
apply and Spread
apply used to be the only way to pass an array of values as separate arguments:
const nums = [4, 9, 2];
console.log(Math.max.apply(null, nums)); // 9
console.log(Math.max(...nums)); // 9, the modern equivalentMath.max ignores this, so null is a conventional placeholder. Spread syntax is now the clearer choice in this case. apply remains useful when you need to set this and forward an argument list you received, such as in a wrapper:
function logged(fn) {
return function (...args) {
console.log(`calling ${fn.name} with`, args);
return fn.apply(this, args); // forward both this and arguments
};
}
const account = {
balance: 100,
deposit(amount) {
this.balance += amount;
return this.balance;
}
};
account.deposit = logged(account.deposit);
console.log(account.deposit(50)); // logs the call, then 150The wrapper is a regular function, so it receives account as this through implicit binding. fn.apply(this, args) passes that this on to the original method. Writing fn(...args) here would drop this and break deposit. fn.call(this, ...args) would work equally well, so choosing between call and apply here is a matter of style.
Edge Cases and Gotchas
Very large argument arrays
apply and spread both put every element on the call stack as a separate argument. Engines cap the number of arguments, and the limit varies by engine. Arrays with hundreds of thousands of elements can throw a RangeError. For large data, use a loop or reduce instead:
const big = Array.from({ length: 500000 }, (_, i) => i);
// Math.max.apply(null, big); // may throw RangeError in some engines
const max = big.reduce((a, b) => (a > b ? a : b), -Infinity);
console.log(max); // 499999Arrow functions ignore thisArg
An arrow function has no this of its own, so call and apply cannot set one. The arguments still pass through; only thisArg is silently dropped. The arrow functions chapter covers this in detail.
const arrow = () => typeof this;
console.log(arrow.call({ a: 1 }) === arrow()); // trueCommon mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `fn.call(['a', 'b'])` | The array becomes `this`; no arguments are passed | `fn.call(obj, 'a', 'b')` or `fn.apply(obj, ['a', 'b'])` |
| `fn.apply(obj, 'a', 'b')` | Second argument is the string `'a'`, which is not an object, so `apply` throws a TypeError, and `'b'` would be ignored anyway | Wrap the arguments in an array |
| `fn.call(obj)()` | `call` already invoked `fn`; this tries to call its return value | Drop the extra parentheses |
| `setTimeout(obj.method.call(obj), 100)` | Runs immediately and schedules the return value | Use `bind` or a wrapper function |
| Expecting `call` to override a function from `bind` | The bound `this` wins | See the next chapter |
The last two rows mark the limits of call and apply. They decide this for one invocation that you write yourself, right now. When the invocation happens later, elsewhere, or repeatedly, you need a function that carries its this with it.
Exercise
In a CommonJS file (sloppy mode), what do show.call('hi') and strictShow.call('hi') return for function show() { return typeof this; } and function strictShow() { 'use strict'; return typeof this; }, and why do they differ?
Show answer
show.call('hi') returns 'object' and strictShow.call('hi') returns 'string'. In a sloppy function, a primitive thisArg is boxed into its wrapper object (a String object). In a strict function, thisArg is passed through unchanged. The mode of the called function decides which rule applies.
Exercise
A wrapper is written as function wrap(fn) { return function (...args) { return fn(...args); }; } and then used as user.save = wrap(user.save). Calling user.save() throws "Cannot read properties of undefined". Explain the bug and fix it.
Show answer
The inner function receives user as this through implicit binding, but fn(...args) is a plain call, so the original save gets default binding (undefined in strict code). Forward this explicitly with return fn.apply(this, args); or return fn.call(this, ...args);. The inner function must stay a regular function, not an arrow, so that it receives its own this from the call site.
Exercise
Given const list = { 0: 3, 1: 7, 2: 5, length: 3 };, write one expression using call or apply that returns the sum of its values, and one that returns the largest value.
Show answer
Sum: Array.prototype.reduce.call(list, (a, b) => a + b, 0) returns 15. Largest: Math.max.apply(null, list) returns 7, because apply accepts array-like objects as its argument list. Math.max(...Array.from(list)) also works.