Taking a look at code from Leaflet api
My question is why wrapperFn.apply(context, args);</code> and <code>fn.apply(context, args);
using apply()
and not call()
.
How do you know which one to use ?
Confused because I don't know ahead of time if my passing function is using an array or not.
limitExecByInterval: function (fn, time, context) {
var lock, execOnUnlock;
return function wrapperFn() {
var args = arguments;
if (lock) {
execOnUnlock = true;
return;
}
lock = true;
setTimeout(function () {
lock = false;
if (execOnUnlock) {
wrapperFn.apply(context, args);
execOnUnlock = false;
}
}, time);
fn.apply(context, args);
};
},
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.
So to shortly recap: call is faster than apply because the input parameters are already formatted as necessary for the internal method.
The call, bind and apply methods can be used to set the this keyword independent of how a function is called. The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.
Summary. call : binds the this value, invokes the function, and allows you to pass a list of arguments. apply : binds the this value, invokes the function, and allows you to pass arguments as an array. bind : binds the this value, returns a new function, and allows you to pass in a list of arguments.
Apply takes a single array of arguments, useful for method chaining, the javascript equivalent of calling super. in Java etc.
function makeNoise() {
Foo.prototype.makeNoise.apply(this, arguments);
}
Call takes list of parameters, more useful other situations where the arguments are only available as single variables.
fn.call(this, x, y, z);
which would just be shorthand for
fn.apply(this, [x, y, z])
Given you have an array of arguments you need to use apply()
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