Let's say that I have a functionA defined like this:
functionA = function(myObject, someParams) {
myObject.save_some_data = someParams;
myObject.processed = true;
}
I can then call it and pass an object to work on as functionA(someObject, someParams)
.
I can, however, transform this example with apply()
:
functionA = function(someParams) {
this.save_some_data = someParams;
this.processed = true;
}
functionA.apply(someObject, [someParams]);
Both approaches seems to be achieving the same goal, or am I missing something?
But since apply()
does exist in JavaScript, what are the benefits of using it instead of having my functions accept this
as a first argument?
The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.
Difference between call() and apply() method: The only difference is call() method takes the arguments separated by comma while apply() method takes the array of arguments. Example 1: This example uses call() method to call a function.
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.
apply
is going to use someParams
as an array of arguments; call
would actually do the same thing:
functionA.call(someObject, someParams);
There are no benefits except for style. Passing someObject
as an argument is probably going to make more sense in most cases, but it’s really up to you and which one you like best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With