Method Reuse
With the call[]
method, you can write a method that can be used on different objects.
All Functions are Methods
In JavaScript all functions are object methods.
If a function is not a method of a JavaScript object, it is a function of the global object [see previous chapter].
The example below creates an object with 3 properties, firstName, lastName, fullName.
Example
const person = {
firstName:"John",
lastName: "Doe",
fullName: function [] {
return this.firstName + " " + this.lastName;
}
}
// This will return "John Doe":
person.fullName[];
Try it Yourself »
In the example above, this
refers to the person object.
this.firstName means the firstName property of this.
Same as:
this.firstName means the firstName property of person.
What is this?
In JavaScript, the this
keyword refers to an object.
Which object depends on how this
is being invoked [used or called].
The this
keyword refers to different objects depending on how it is used:
In an object method, this refers to the object.
|
Alone, this refers to the global object.
|
In a function, this refers to the global object.
|
In a function, in strict mode, this is undefined .
|
In an event, this refers to the element that received the event.
|
Methods like call[] , apply[] , and bind[] can refer this to any object.
|
The JavaScript call[] Method
The call[]
method is a predefined JavaScript method.
It can be used to invoke [call] a method with an owner object as an argument [parameter].
With call[]
, an object can use a method belonging to another object.
This example calls the fullName method of person, using it on person1:
Example
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];
Try it Yourself »
This example calls the fullName method of person, using it on person2:
Example
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];
Try it Yourself »
The call[] Method with Arguments
The call[]
method can accept arguments:
Example
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"];
Try it Yourself »
Summary: in this tutorial, you will learn about the JavaScript call[]
method and how to use it more effectively.
Introduction to the JavaScript call[] method
In JavaScript, a function is an instance of the Function
type. For example:
Code language: JavaScript [javascript]
function add[x, y] { return x + y; } console.log[add instanceof Function]; // true
The Function.prototype
type has the call[]
method with the following syntax:
Code language: JavaScript [javascript]
functionName.call[thisArg, arg1, arg2, ...];
In
this syntax, the call[]
method calls a function functionName
with the arguments [arg1
, arg2
, …] and the this
set to thisArg
object inside the function.
- The
thisArg
is the object that thethis
object references inside the functionfunctionName
. - The
arg1
,arg2
, .. are the function arguments passed into thefunctionName
.
The call[]
method returns the result of calling the functionName[]
.
The following example defines the add[]
function and calls
it normally:
function add[x, y] { return x + y; } let result = add[10, 20]; console.log[result]; // 30
Code language: JavaScript [javascript]
The following calls the add[]
function but use the call[]
method instead:
Code language: JavaScript [javascript]
function add[x, y] { return x + y; } let result = add.call[this, 10, 20]; console.log[result]; // 30
By default, the this
inside the function is set to the global object i.e., window
in the web browsers and global
in Node.js.
Note that in the strict mode, the this
inside the function is set to undefined
instead of the global object.
Consider the following example:
Code language: JavaScript [javascript]
var greeting = 'Hi'; var messenger = { greeting: 'Hello' } function say[name] { console.log[this.greeting + ' ' + name]; }
Inside the say[]
function, we reference the greeting
via the this
value. If you just invoke the say[]
function via the call[]
method as follows:
Code language: JavaScript [javascript]
say.call[this,'John'];
It’ll show the following output to the console:
Code language: JavaScript [javascript]
"Hi John"
However, when you invoke the call[]
method of say
function object and pass the messenger
object as the this
value:
Code language: JavaScript [javascript]
say.call[messenger,'John'];
The output will be:
Code language: JavaScript [javascript]
"Hello John"
In this case, the this
value inside the say[]
function references the
messenger
object, not the global object.
Using the JavaScript call[] method to chain constructors for an object
You can use the call[]
method for chaining constructors of an object. Consider the following example:
Code language: JavaScript [javascript]
function Box[height, width] { this.height = height; this.width = width; } function Widget[height, width, color] { Box.call[this, height, width]; this.color = color; } let widget = new Widget['red', 100, 200]; console.log[widget];
Output:
Code language: JavaScript [javascript]
Widget { height: 'red', width: 100, color: 200 }
In this example:
- First, initialize the
Box
object with two properties:height
andwidth
. - Second, invoke the
call[]
method of theBox
object inside theWidget
object, set thethis
value to theWidget
object.
Using the JavaScript call[] method for function borrowing
The following example illustrates how to use the call[] method for borrowing functions:
Code language: JavaScript [javascript]
const car = { name: 'car', start[] { console.log['Start the ' + this.name]; }, speedUp[] { console.log['Speed up the ' + this.name]; }, stop[] { console.log['Stop the ' + this.name]; }, }; const aircraft = { name: 'aircraft', fly[] { console.log['Fly']; }, }; car.start.call[aircraft]; car.speedUp.call[aircraft]; aircraft.fly[];
Output:
Start the aircraft Speed up the aircraft Fly
Code language: JavaScript [javascript]
How it works.
First, define a car object with one property name and three methods start
, speedUp
, and stop
:
Code language: JavaScript [javascript]
const car = { name: 'car', start[] { console.log['Start the ' + this.name]; }, speedUp[] { console.log['Speed up the ' + this.name]; }, stop[] { console.log['Stop the ' + this.name]; }, };
Second, define the aircraft object with one property name and a method:
Code language: JavaScript [javascript]
const aircraft = { name: 'aircraft', fly[] { console.log['Fly']; }, };
Third, call the start[]
and speedUp[]
method of the
car
object and the fly[]
method of the aircraft
object. However, passing the aircraft
as the first argument into the start[]
and speedUp[]
methods:
Code language: JavaScript [javascript]
car.start.call[aircraft]; car.speedUp.call[aircraft]; aircraft.fly[];
Inside the start[]
and speedUp[]
methods, the this
references the aircraft
object, not the car
object. Therefore, the this.name
returns the 'aircraf'
string. Hence, the methods output the following message:
Code language: plaintext [plaintext]
Start the aircraft Speed up the aircraft
Technically, the aircraft
object borrows the start[]
and speedUp[]
method of the car
object. And
function borrowing refers to an object that uses a method of another object.
The following example illustrates how the arguments
object borrows the filter[]
method of the Array.prototype
via the call[]
function:
Code language: JavaScript [javascript]
function isOdd[number] { return number % 2; } function getOddNumbers[] { return Array.prototype.filter.call[arguments, isOdd]; } let results = getOddNumbers[10, 1, 3, 4, 8, 9]; console.log[results];
Output:
Code language: JavaScript [javascript]
[ 1, 3, 9 ]
How it works.
First, define the isOdd[]
function that returns true if the number is an odd number:
Code language: JavaScript [javascript]
function isOdd[number] { return number % 2; }
Second, define the getOddNumbers[]
function that accepts any number of arguments and returns an array that contains only odd numbers:
Code language: JavaScript [javascript]
function getOddNumbers[] { return Array.prototype.filter.call[arguments, isOdd]; }
In this example, the arguments
object borrows the filter[] method of the Array.prototype
object.
Third, call the getOddNumbers[]
function:
Code language: JavaScript [javascript]
let results = getOddNumbers[10, 1, 3, 4, 8, 9]; console.log[results];
In this tutorial, you have learned about the JavaScript call[]
method and how to use it more effectively.
Was this tutorial helpful ?