14

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);
    };
},
airnet
  • 2,245
  • 4
  • 27
  • 33
  • 2
    http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply – Gaurav Pandey Jan 07 '15 at 06:58
  • yes apply uses array, and call uses list(comma separated variables). what if I am passing a list of arguments in my function. Then I should use call() ? – airnet Jan 07 '15 at 06:59

1 Answers1

3

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()

Adam
  • 32,907
  • 8
  • 89
  • 126
  • But I don't ahead of time if my passing function is using an array or not ? That's why i'm confused – airnet Jan 07 '15 at 07:03
  • arguments is a built-in magic variable which is populated with the arguments to the current function call, in your code you save it as args earlier. – Adam Jan 07 '15 at 07:05