Thursday 9 November 2017

javascript - What is the difference between call and apply?

itemprop="text">

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 aforementioned methods? When is it best to
use call over apply and vice
versa?



Answer




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 href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply"
rel="noreferrer">apply and href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call"
rel="noreferrer">call.



Pseudo
syntax:




theFunction.apply(valueForThis,
arrayOfArgs)



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



There is also, as
of ES6, the possibility to href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator"
rel="noreferrer">spread the array for use with the
call function, you can see the compatibilities href="http://kangax.github.io/compat-table/es6/"
rel="noreferrer">here.



Sample
code:



data-hide="false" data-console="true"
data-babel="false">

class="snippet-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






No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...