Function Call in JavaScript
? Function.prototype.call() in JavaScript
What is call()?
call()is a method that invokes a function immediately, allowing you to specify the value ofthisinside that function.It also lets you pass arguments one by one.
Syntax
func.call(thisArg, arg1, arg2, ...);thisArg: The value to use asthisinside the function.arg1, arg2, ...: Arguments passed individually to the function.
Example 1: Basic Usage
function greet(greeting, punctuation) { console.log(greeting + ", " + this.name + punctuation);}const person = { name: "Alice" };greet.call(person, "Hello", "!"); // Output: Hello, Alice!Example 2: Using call() to Borrow Methods
const person1 = { fullName: function() { return this.firstName + " " + this.lastName; }};const person2 = { firstName: "John", lastName: "Doe"};// Borrow fullName method from person1console.log(person1.fullName.call(person2)); // Output: John DoeDifference Between call() and apply()
| Method | Arguments Format | Calls Immediately? |
|---|---|---|
call() | Comma-separated arguments | Yes |
apply() | Array or array-like | Yes |
Summary
| Feature | call() |
|---|---|
| Calls function | Yes |
Sets this | Yes |
| Arguments | Passed one by one |
| Returns result | Yes |
Want me to show how to use call() for function borrowing or variadic functions?