Differences between call and apply in JavaScript

Suppose that you have a JavaScript function

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

Are there any differences between func.apply();, func.call(); and func();?

The apply() method is identical to call(), except that apply() requires an array as the second parameter. The array represents the arguments for the target method.  In other words, apply() lets you invoke the function with arguments as an array; while call() requires the parameters to be listed explicitly.

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

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");

// 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.

Use apply() if you don’t know the number of arguments you will be passing or if they are already in an array.  Use call() otherwise because there is no need to wrap the arguments in an array.

Douglas Crockford mentions briefly the difference between the two, which may help explain the performance difference

Crockford on JavaScript – Act III: Function the Ultimate

Crockford on JavaScript – Act III: Function the Ultimate

5 years ago
Yahoo!’s JavaScript architect Douglas Crockford continues his lecture series on the JavaScript programming language with a discussion of functions in JavaScript. “Functions are the very best part of JavaScript,” Crockford says. “It’s where the power is, it’s where the beauty is.” Watch the video to learn why.

Leave a Reply

Be the First to Comment!

Notify of
avatar

wpDiscuz