The difference is:
The call()
method takes arguments separately.
The apply()
method takes arguments as an array.
The apply() method is very handy if you want to use an array instead of an argument list.
The apply()
method accepts arguments in an array:
Example(1)
<script> var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:"John", lastName: "Doe" } var x = person.fullName.apply(person1, ["Oslo", "Norway"]); document.getElementById("demo").innerHTML = x; </script>
Compared with the call()
method:
<script> var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:"John", lastName: "Doe" } var x = person.fullName.apply(person1, ["Oslo", "Norway"]); document.getElementById("demo").innerHTML = x; var x2 = person.fullName.call(person1, "Oslo", "Norway"); document.getElementById("demo1").innerHTML = x2; </script>
Complete Code For The Difference Between call() and apply()
<!DOCTYPE html> <html> <head> <title>Differentiate Between Call And Apply Methods In JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">Differentiate Between Call And Apply Methods In JavaScript</h1> </div> <div class="well"> <h2 id="demo"></h2> <h2 id="demo1"></h2> <script> var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:"John", lastName: "Doe" } var x = person.fullName.apply(person1, ["Oslo", "Norway"]); document.getElementById("demo").innerHTML = x; var x2 = person.fullName.call(person1, "Oslo", "Norway"); document.getElementById("demo1").innerHTML = x2; </script> </div> </div> </body> </html>