Difference between call() and apply() method of JavaScript
Many people get confused with these two functions in JavaScript, most of the time people think that we can pass an object in apply() and access it with this which is not possible with the call() method. But that is not the case, let’s see an example which will make it more clear.
Using call() method:
[js]
(function sum(a,b,c) {
var i, k=0;
var num = arguments.length;
for (i = 0; i < num; i++) {
k+= arguments[i];
}
console.log(this.toString()); //prints body of the function passed i.e., test()
console.log(k); //prints the sum in console
this(); // this will call the test() function passed to sum
return k; //returns sum
}).call(function test() {
console.log(10); //prints 10 in console
},10,100);
[/js]
Using apply() method:
[js] (function sum(a,b) {
var i, k=0;
var num = arguments.length;
for (i = 0; i
So the basic difference between both the methods is that in call() method we have to pass comma separated arguments and in apply() method we have to pass an array. If you have any queries then do let me know in comments section below.
in call method if i pass array means it will consider as one argument am i correct