Function.prototype.call and apply
func.call(thisArg, ...args)
func.apply(thisArg, args)Invoke a function with a chosen this value. call takes a list of arguments; apply takes an array or array-like list.
| Parameter | Description |
|---|---|
thisArg | The value to use as this when calling func. In strict mode it is used as given. |
args | call accepts individual arguments. apply accepts one array or array-like object of arguments. |
Returns: The return value of func.
Throws
TypeError— Thrown when the value being called is not callable, or when apply’s argument list is not an object.
function make() {
return {
n: 1,
regular: function (x) { return this.n + x; },
};
}
const methods = make.call({ n: 7 });
console.log(methods.regular(2));
console.log(methods.regular.call({ n: 10 }, 2));
console.log(methods.regular.apply({ n: 10 }, [3]));
try {
Function.prototype.call.call(undefined);
} catch (error) {
console.log(error.name);
}Expected output
3
12
13
TypeErrorRelated: bind and arrow functions, TypeScript this types, Official call