Function Invocation with call and apply
When invoking functions, programmers often encounter the options of using Function.prototype.apply() or Function.prototype.call(). This article explores the distinctions and use cases for both methods.
apply() vs. call()
The fundamental difference lies in how they handle function arguments:
Syntax
Method | Syntax |
---|---|
apply() | function.apply(thisArg, [arg1, arg2, ...]) |
call() | function.call(thisArg, arg1, arg2, ...) |
Mnemonics
To remember the difference:
Use Cases
Performance Considerations
Both methods have similar performance characteristics. In ES6 and later, the spread operator (...) can be used with call(), providing a more concise alternative to apply().
Example
Consider the following function:
function greet(name, occupation) { console.log(`Hello, my name is ${name} and I'm a ${occupation}.`); }
Invoking the function using apply() and call():
greet.apply(undefined, ["John", "engineer"]); greet.call(undefined, "Mary", "doctor");
This will output:
Hello, my name is John and I'm a engineer. Hello, my name is Mary and I'm a doctor.
The above is the detailed content of `call()` vs. `apply()`: When to Use Which Function Invocation Method?. For more information, please follow other related articles on the PHP Chinese website!