0

Taking a look at code from Leaflet API

Getting lost with arguments and closures.

My second log output of arguments is an empty array. Shouldn't be the same at the first log.

limitExecByInterval: function (fn, time, context) {
    var lock, execOnUnlock;

    // Log output 1
    console.log(arguments);//[foo(), 10000, Window a.html]

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

        //Log output 2
        console.log(args) //[]

        fn.apply(context, args);
    };
},
1
  • Arguments are different for the two functions..Thus different console log output. Commented Jan 7, 2015 at 8:42

2 Answers 2

1

Shouldn't be the same at the first log.

No. Each function has its own arguments object. The second console.log call will log the arguments passed to wrapperFn, which doesn't seem to receive any in your test.

Sign up to request clarification or add additional context in comments.

Comments

1

This is because arguments is a keyword inside a function , and does not behave like normal variables.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

You would need to store arguments in another variable to get the desired behavior

limitExecByInterval: function (fn, time, context) {
        var lock, execOnUnlock;

        // Log output 1
        console.log(arguments);//[foo(), 10000, Window a.html]
        var myArgs = arguments ;

        return function wrapperFn() {
            var args = myArgs;  /* not using the keyword 'arguments' here */

            if (lock) {
                execOnUnlock = true;
                return;
            }

            lock = true;

            setTimeout(function () {
                lock = false;

                if (execOnUnlock) {
                    wrapperFn.apply(context, args);
                    execOnUnlock = false;
                }
            }, time);

            //Log output 2
            console.log(args) //[]  This will print an array now.

            fn.apply(context, args);
        };
    },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.