Function.prototype.call
Calls a function with a given this and arguments.
Available since: ES3
Syntax
fn.call(thisArg, arg1, arg2, /* … */)Parameters
| Parameter | Type | Description |
|---|---|---|
| thisArg | any | The this value for the call. |
| arg1, … | any | The function's arguments. |
Return value
anyThe function's result.
Examples
One function for different objects:
function introduce(greeting) {
return `${greeting}, I am ${this.name}`;
}
console.log(introduce.call({ name: 'Anna' }, 'Hi'));
console.log(introduce.call({ name: 'Oleg' }, 'Hello'));Output:
Hi, I am Anna
Hello, I am OlegNotes
call() runs the function immediately, while bind() returns a new function for later. The only difference from apply() is how arguments are passed.
See also
- Function.prototype.apply — Calls a function with a given this and an array of arguments.
- Function.prototype.bind — Creates a copy of a function with a fixed this and, optionally, arguments.
In the tutorial
- this, call, apply and bind — How this is determined in JavaScript, why a method loses its context, and how to set this by hand with call, apply and bind.