What is call in Javascript and when to use
What is call in Javascript and when to use
The call method in javascript helps you to call a function with a given this value. And the call method is almost similar to the application method. The major difference is that the call method can receive an argument list and apply method can only receive a single array of arguments.
For understanding how call works properly in Javascript, its necessary to understand how this keyword works with object methods. Consider the below example,
The below code returns an undefined when you call a different function in other functions. Its because it loses this instance as its window level scope.
function Employee(name, role) { this.name = name; this.role = role; } function Food(name, role) { Employee(name, role); this.category = 'Tallywood'; } console.log(new Food('Rajani', 'Actor')); // output // undefined
To solve the above problem, call method help in Javascript, now consider the modified code
function Employee(name, role) { this.name = name; this.role = role; } function Food(name, role) { Employee.call(this,name, role); this.category = 'Tallywood'; } console.log(new Food('Rajani', 'Actor').name); // output // Rajani
Also, read Promises in Javascript?
One thought on “What is call in Javascript and when to use”
Comments are closed.