-2

I have seen lot of java-script code,that uses call as well as apply methods to invoke the function. I am little bit confuse about the exact difference and in what which one to use in what condition.

YaSh
  • 51
  • 7
  • look at the mdn doc [call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) – Arun P Johny Dec 14 '13 at 11:08

1 Answers1

3

They're not jQuery things, they're JavaScript things.

They do the same thing: They call the given function using a specific value for this within the function call. The only difference is how you specify the arguments to pass to the function. With call, you specify them as a series of discrete arguments (after the first one, which is what to use as this). With apply, you specify them as an array (again after the first arg, which is what to use as this).

So say we have:

function foo(a, b, c) {
   console.log("this = " + this);
   console.log("a = " + a);
   console.log("b = " + b);
   console.log("a = " + c);
}

These two calls do exactly the same thing:

foo.call("bar", 1, 2, 3);
// Note --------^--^--^--- a series of discrete args

foo.apply("bar", [1, 2, 3]);
// Note ---------^-------^-- args as an array

In both cases, we see:

this = bar
a = 1
b = 2
c = 3
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639