All In One Script



PHP,HTLM,CSS,Jquery,AJAX,Javascript and etc doubts and sample codes

  • Home
  • Javascript
  • PHP
  • CSS
  • SQL/MYSQL

What is the difference between call and apply?

by Blogger 4:52:00 AM dynamic Function Javascript

What is the difference between call and apply?

What is the difference between using call and apply to invoke a function?
var func = function(){
  alert('hello!');
};
func.apply();
vs
func.call();
Are there performance differences between the two methods? When is it best to use call over apply and vice versa?


Solution:

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

// Output: 

// My name is John and I am a fireman.
// My name is Susan and I am a school teacher.
// My name is Claude and I am a mathematician.
// My name is Matthew and I am a physicist.


http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply
READ MORE
SHARE :

Search This Blog

Followers

  • Popular
  • Recent
  • Comments

Instagram

About

Popular Posts

statcounter



statcounter



Template Created By ThemeXpose & Blogger Templates