1. Introduction
The call()
method calls a function. While calling this method you can provide this
argument and other arguments.
All the following are valid versions of call()
method:
call() call(thisArgument) call(thisArgument, arg1) call(thisArgument, arg1, arg2) call(thisArgument, arg1, ... , argN)
thisArgument
is the optional argument which is used as this
. arg
1….argN
are the optional arguments provided to the function.
2. Examples of call()
Example 1: Using call() to call a function
In this example, we are using call()
without any argument.
function hello() { console.log("hello world"); } hello.call(); //hello world
Example 2: Using call() with this
In this example, while using call()
, we are passing one argument. Since the first argument is this
, this
will refer to { msg: "hello world" }
.
function hello() { console.log(this.msg); } hello.call({ msg: "hello world" }); // hello world
Example 3: Using call() with this and argument
function hello(msg) { console.log(msg); } hello.call(this, "hello world"); //hello world
Example 4: Constructor chaining using call() method
Constructor chaining is similar to that of in Java. In this example, we are creating an object of Car
. Inside the function Car
, we are calling function Vehicle
and setting properties wheels
and color
. While calling Vehicle
we are using this
, it will set properties wheels
and color
of Car
.
function Vehicle(wheels, color) { this.wheels = wheels; this.color = color; } function Car(wheels, color) { Vehicle.call(this, wheels, color); this.brand = "audi"; } let car = new Car(4, "red"); console.log(car);
Example 5: Using call() to invoke an anonymous function
Call can be used to invoke an anonymous function. Following is a simple example:
(function (msg) { console.log(msg); }.call(this, "hello"));
3. Conclusion
In this tutorial, we discussed call()
method of JavaScript. It is a very important question for interview. You may find the use of this method in old code.
We have hope this tutorial was informative.