Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between call and apply?

What is the difference between using Function.prototype.apply() and Function.prototype.call() to invoke a function?

var func = function() {   alert('hello!'); }; 

func.apply(); vs func.call();

Are there performance differences between the two aforementioned methods? When is it best to use call over apply and vice versa?

like image 244
John Duff Avatar asked Dec 31 '09 19:12

John Duff


People also ask

Why do we use call and apply?

call and apply are very similar—they invoke a function with a specified this context, and optional arguments. The only difference between call and apply is that call requires the arguments to be passed in one-by-one, and apply takes the arguments as an array.

Which is faster call or apply?

So to shortly recap: call is faster than apply because the input parameters are already formatted as necessary for the internal method.

What is difference between call bind and apply?

Summary. call : binds the this value, invokes the function, and allows you to pass a list of arguments. apply : binds the this value, invokes the function, and allows you to pass arguments as an array. bind : binds the this value, returns a new function, and allows you to pass in a list of arguments.

What is call apply?

Call invokes the function and allows you to pass in arguments one by one. Apply invokes the function and allows you to pass in arguments as an array. Bind returns a new function, allowing you to pass in a this array and any number of arguments.


2 Answers

The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."

See MDN's documentation on apply and call.

Pseudo syntax:

theFunction.apply(valueForThis, arrayOfArgs)

theFunction.call(valueForThis, arg1, arg2, ...)

There is also, as of ES6, the possibility to spread the array for use with the call function, you can see the compatibilities here.

Sample code:

function theFunction(name, profession) {     console.log("My name is " + name + " and I am a " + profession +"."); } theFunction("John", "fireman"); theFunction.apply(undefined, ["Susan", "school teacher"]); theFunction.call(undefined, "Claude", "mathematician"); theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator
like image 178
flatline Avatar answered Sep 28 '22 09:09

flatline


K. Scott Allen has a nice writeup on the matter.

Basically, they differ on how they handle function arguments.

The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method."

So:

// assuming you have f function f(message) { ... } f.call(receiver, "test"); f.apply(receiver, ["test"]); 
like image 27
notnoop Avatar answered Sep 28 '22 10:09

notnoop