Sub topic 6
Setting this with call and apply
This chapter assumes you know how plain function calls and method calls set this, and why a method can lose its this when you pull it off its object. In those cases the engine picks this for you based on the call site. call and apply let you pick it yourself.
The Working Model
Every regular function inherits two methods from Function.prototype: call and apply. Both invoke the function right away. The first argument becomes this, and the remaining arguments go to the function. The two methods differ only in how you pass those arguments:
| Method | Signature | Arguments passed as |
|---|---|---|
| `call` | `fn.call(thisValue, a, b, c)` | A comma-separated list |
| `apply` | `fn.apply(thisValue, [a, b, c])` | One array or array-like object |
A mnemonic: apply takes an array, call takes commas.
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const ada = { name: 'Ada' };
console.log(greet.call(ada, 'Hello', '!')); // 'Hello, Ada!'
console.log(greet.apply(ada, ['Hi', '?'])); // 'Hi, Ada?'greet is not a property of ada, and it does not need to be. The call site greet.call(ada, ...) tells the engine to use ada as this for this one invocation. The next plain call to greet() falls back to default binding.
Common Uses
Borrowing Methods
Methods that work on "anything with a length and indexed elements" can run against objects that don't inherit them. This was the classic way to turn arguments into a real array:
function listArgs() {
const args = Array.prototype.slice.call(arguments);
return args.join(' | ');
}
console.log(listArgs('a', 'b', 'c')); // 'a | b | c'
const arrayLike = { 0: 'x', 1: 'y', length: 2 };
console.log(Array.prototype.map.call(arrayLike, (s) => s.toUpperCase())); // ['X', 'Y']Modern code would use Array.from(arguments) or rest parameters, but the borrowing pattern still turns up in libraries and when you call a method that an object has shadowed, such as Object.prototype.hasOwnProperty.call(obj, key).
Spreading an Array into Arguments
Before ES2015, apply was the only way to pass an array as separate arguments:
const scores = [72, 95, 88];
console.log(Math.max.apply(null, scores)); // 95
console.log(Math.max(...scores)); // 95, the modern equivalentMath.max ignores this, so null is a placeholder. When this is irrelevant, prefer spread syntax because it reads more clearly. Use apply when you need to set this and spread arguments in the same call.
Common Errors
Passing null or a Primitive as this
What the function sees depends on whether the function is strict:
function sloppyThis() {
return this;
}
function strictThis() {
'use strict';
return this;
}
console.log(sloppyThis.call(null) === globalThis); // true
console.log(typeof sloppyThis.call(5)); // 'object', boxed into a Number
console.log(strictThis.call(null)); // null
console.log(typeof strictThis.call(5)); // 'number'In sloppy mode, null and undefined are replaced with globalThis, and primitives are wrapped in objects. In strict code, which includes modules and classes, the value arrives unchanged. If you pass null to a sloppy function that writes to this, it will write global variables without any warning.
Expecting the Binding to Stick
call and apply affect a single invocation and leave the function itself unchanged. If you pass greet.call(ada) as a callback, you pass the result of calling it, not a function. To create a function whose this stays fixed for later calls, use bind, which the next chapter covers.
Mixing Up the Argument Shapes
greet.apply(ada, 'Hello', '!') throws a TypeError because 'Hello' is not an array-like object... actually, strings are array-like, so it treats 'Hello' as five separate arguments: 'H', 'e', and so on. greet.call(ada, ['Hello', '!']) passes the whole array as greeting. Neither call fails loudly, so check the argument shape whenever the output looks strange.
Exercise
Given function describe(unit) { return this.value + unit; } and const reading = { value: 21 };, write one expression using call and one using apply that both return '21°C'. Then explain what describe.call(null, '°C') returns in a non-strict script and why.
Show answer
describe.call(reading, '°C') and describe.apply(reading, ['°C']) both return '21°C'. In a non-strict script, describe.call(null, '°C') replaces null with globalThis, so this.value reads globalThis.value. That is usually undefined, so the result is 'undefined°C'. The undefined is converted to a string and concatenated.
Exercise
Why does Math.max.apply(null, [3, 9, 4]) work even though null is passed as this?
Show answer
Math.max never reads this. It only uses its arguments, so the first argument to apply is a placeholder, and apply's real job here is spreading the array into separate arguments. Math.max(...[3, 9, 4]) does the same thing.