Javascript Function Call
The call()
method can be used on any function in JavaScript. When you call a function using call()
, you can specify the this value of the function.
The this value refers to the object that the function is being called on. You can also pass arguments to the function using call()
.
Here's an example of how to use call()
:
const person = {
firstName: "John",
lastName: "Doe",
};
function fullName() {
return this.firstName + " " + this.lastName;
}
// using call() to call the function fullName() on the person object
const fullNameResult = fullName.call(person);
console.log(fullNameResult); // "John Doe"
In this example:
- We have an object person with firstName and lastName properties, and a function
fullName()
that returns the full name of a person. - We call the
fullName()
function usingcall()
on the person object, which sets the this value of the function to the person object.
this
keyword with call()
When you call a function using call()
, you can specify the this value for that function. The this value is passed as the first argument to call()
. Any additional arguments to the function are passed as subsequent arguments to call()
.
As an example:
const person = {
firstName: "John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
const fullNameResult = person.fullName.call(person);
console.log(fullNameResult); // "John Doe"
In this example:
- We have an object person with a
fullName()
method that returns the full name of the person. - We call the
fullName()
method usingcall()
on the person object, which sets the this value of the method to the person object.
When the fullName()
method is called with call()
, this refers to the person object. This allows us to access the firstName and lastName properties of the person object within the fullName()
method.
The call()
Method with Arguments
You can use the call()
method to pass arguments to a function. When you call a function using call()
, you can pass in any number of arguments after the first thisArg argument, and these arguments will be passed to the function as separate parameters.
As an example:
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
const person = {
firstName: "John",
lastName: "Doe",
};
const fullNameResult = fullName.call(person, person.firstName, person.lastName);
console.log(fullNameResult); // "John Doe"
In this example:
- We have a
fullName()
function that takes two arguments: firstName and lastName. - We also have a person object with firstName and lastName properties.
- We pass the person object as the first argument to
call()
. - We then pass the firstName and lastName properties of the person object as separate arguments after the thisArg argument.