How to Use call() in JavaScript: Syntax and Examples
In JavaScript,
call() is a method used to invoke a function with a specified this context and individual arguments. It allows you to control what this refers to inside the function when calling it.Syntax
The call() method syntax is:
functionName.call(thisArg, arg1, arg2, ...)
Here, functionName is the function you want to call.
thisArg is the object to use as this inside the function.
arg1, arg2, ... are the arguments passed to the function.
javascript
functionName.call(thisArg, arg1, arg2, ...);
Example
This example shows how to use call() to set this inside a function and pass arguments:
javascript
const person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + ", " + city + ", " + country; } }; const person1 = { firstName: "John", lastName: "Doe" }; const result = person.fullName.call(person1, "New York", "USA"); console.log(result);
Output
John Doe, New York, USA
Common Pitfalls
Common mistakes when using call() include:
- Not passing the correct
thisobject, which can cause errors or unexpected results. - Passing arguments as an array instead of individual values (use
apply()for arrays). - Forgetting that
call()immediately invokes the function.
javascript
const obj = { name: "Alice" }; function greet(greeting) { console.log(greeting + ", " + this.name); } // Wrong: passing arguments as array (does not work with call) greet.call(obj, ["Hello"]); // Outputs: Hello, Alice (but argument is an array, not string) // Right: pass arguments individually greet.call(obj, "Hello"); // Outputs: Hello, Alice
Output
Hello, Alice
Hello, Alice
Quick Reference
| Method | Purpose | Arguments |
|---|---|---|
| call() | Calls function with specified this and individual args | thisArg, arg1, arg2, ... |
| apply() | Calls function with specified this and args as array | thisArg, [argsArray] |
| bind() | Returns new function with bound this and optional args | thisArg, arg1, arg2, ... |
Key Takeaways
call() invokes a function with a specified this value and individual arguments.Always pass the correct object as
thisArg to control the function context.Use individual arguments with
call(), not arrays (use apply() for arrays).call() immediately runs the function; it does not create a new function.It helps reuse functions with different objects easily.