Home >Web Front-end >JS Tutorial >Call vs. Apply in JavaScript: How Do These Function Invocation Methods Differ?
Function Invocation Methods: call vs. apply
In JavaScript, the call and apply methods allow you to invoke functions with custom contexts and arguments. While both methods serve the same purpose, they differ in how they handle argument passing.
call vs. apply: Argument Handling
The key difference lies in how the arguments are supplied to the function:
To remember this distinction, the mnemonic "A for array and C for comma" can be useful.
Syntax:
call:
theFunction.call(valueForThis, arg1, arg2, ...)
apply:
theFunction.apply(valueForThis, arrayOfArgs)
Example:
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");
In this example, the call method is used with comma-separated arguments, while the apply method takes an array of arguments.
Spread Operator:
In ES6 and later, the spread operator can be used to pass an array as arguments to the call method:
theFunction.call(undefined, ...["Matthew", "physicist"]);
Performance and Usage Recommendations:
There are no significant performance differences between call and apply. The choice of which method to use depends on the specific situation:
The above is the detailed content of Call vs. Apply in JavaScript: How Do These Function Invocation Methods Differ?. For more information, please follow other related articles on the PHP Chinese website!