Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using apply() vs call(), which one to use in this case? [duplicate]

Tags:

javascript

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);
    };
},
like image 987
airnet Avatar asked Jan 07 '15 06:01

airnet


People also ask

What is the difference between call () and apply () methods?

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.

Which is faster call or apply?

So to shortly recap: call is faster than apply because the input parameters are already formatted as necessary for the internal method.

What is common feature of call () apply () and bind ()?

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.

What is the difference between call bind and apply?

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.


1 Answers

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

like image 162
Adam Avatar answered Oct 17 '22 09:10

Adam