- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the difference between call and apply in JavaScript?
In JavaScript, .call and .apply are considered a method of function object.
.call method
Count the number of arguments with call method. It accepts one or more arguments as objects.
Here’s the syntax:
.call(object, “argument1”, “argument2”);
.apply method
To use an array as an argument, use .apply. It requires an array as its 2nd argument.
Here’s the syntax:
.apply(object, [“argument1”, “argument[]”]);
Example
Let’s see an example showing both call and apply method:
<!DOCTYPE html> <html> <head> <body> <script> var p = { q: "Hello" } function showResult(v) { document.write(this.q + " " + v); } showResult.call(p, "Amit"); // one or more objects as argument showResult.apply(p, ["World"]); // array as the second argument </script> </body> </head> </html>
Advertisements