带有函数参数数组的闭包

Closures with arguments array of function

本文关键字:闭包 数组 参数 函数      更新时间:2023-09-26

看看 Leaflet API 中的代码

迷失在争论和关闭中。

我的参数的第二个日志输出是一个空数组。在第一个日志中应该不一样。

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

在第一个日志中应该不一样。

不。每个函数都有自己的arguments对象。第二个console.log调用将记录传递给wrapperFn的参数,这在您的测试中似乎没有收到任何参数。

这是因为参数是函数内部的关键字,其行为不像普通变量。

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

您需要将参数存储在另一个变量中才能获得所需的行为

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