Using the call() method, you can write a function that can be applied to different objects by specifying a different this value for each call.
In JavaScript, all functions are considered object methods.
If a function is not a method of a specific object, it becomes a function of the global object (as explained in the previous chapter).
The example below creates an object with three properties: firstName, lastName, and fullName.
| const person = { firstName:“John”, lastName: “Doe”, fullName: function () { return this.firstName + ” “ + this.lastName; } } // This will return “John Doe”: person.fullName(); |
In the example above, this refers to the person object.
this.firstName refers to the firstName property of this.
This is equivalent to:
this.firstName referring to the firstName property of person.
In JavaScript, the this keyword refers to an object.
The object that this refers to depends on how it is used.
|
In an object method, this refers to the object that owns the method. |
|
When used alone, this refers to the global object. |
|
In a function, this refers to the global object. |
|
In strict mode, this is undefined inside a function. |
|
In an event handler, this refers to the element that triggered the event. |
|
Methods like call(), apply(), and bind() allow you to set this to any object. |
|
Note: this is not a variable; it is a keyword. You cannot modify its value.d |
The call() method is a built-in JavaScript method.
It allows you to invoke (call) a method, with the owner object passed as an argument (parameter).
|
Using call(), an object can invoke a method that belongs to another object. |
This example invokes the fullName method of person, applying it to person1.
| const person = { fullName: function() { return this.firstName + ” “ + this.lastName; } } const person1 = { firstName:“John”, lastName: “Doe” } const person2 = { firstName:“Mary”, lastName: “Doe” } // This will return “John Doe”: person.fullName.call(person1); |
This example invokes the fullName method of person, applying it to person2.
| const person = { fullName: function() { return this.firstName + ” “ + this.lastName; } } const person1 = { firstName:“John”, lastName: “Doe” } const person2 = { firstName:“Mary”, lastName: “Doe” } // This will return “Mary Doe” person.fullName.call(person2); |
The call() method can take arguments:
| const person = { fullName: function(city, country) { return this.firstName + ” “ + this.lastName + “,” + city + “,” + country; } } const person1 = { firstName:“John”, lastName: “Doe” } person.fullName.call(person1, “Oslo”, “Norway”); |