【问题标题】:closures - why is this line coded like this?闭包 - 为什么这行代码是这样的?
【发布时间】:2015-03-12 14:58:51
【问题描述】:

我正在查看 Leaflet api。

在 setTimeout 中调用 wrapperFn.apply(context, args); 而不是 fn.apply(context, args); 是否有原因?

我试过了,它给了我相同的输出。但想知道它是否有意义?

函数 a(fn, time, context) {
        变量锁,execOnUnlock;

        返回函数 wrapperFn() {
            var args = 参数;

            如果(锁定){
                execOnUnlock = 真;
                返回;
            }

            锁=真;

            设置超时(函数(){
                锁=假;

                如果(execOnUnlock){
                    wrapperFn.apply(上下文,参数);
                    execOnUnlock = 假;
                }
            }, 时间);

            fn.apply(上下文,参数);
        };
    },

【问题讨论】:

  • wrapperFn 确保不会重复调用fn。使用fn 会失去这种保护。

标签: javascript


【解决方案1】:

该函数为作为第一个参数的函数创建一个包装器,该包装器只能在第二个参数指定的时间间隔内执行。如果您在间隔内再次调用它一次或多次,则最后一次调用将在间隔后自动执行。

var f = a(someFunction, 1000, {});
f(1); // this will execute the function
f(2); // this will not be executed
f(3); // this will be executed after a second
setTimeout(function(){
  f(4); // this will be executed a half second later (two seconds after the first)
}, 1500);

在间隔结束时自动进行的调用会将函数锁定另一个时间间隔。如果代码调用fn 而不是wrapperFn,则该调用不会被锁定,您可以在间隔内再次调用该函数。示例:

var f = a(someFunction, 1000, {});
f(1); // this will execute the function
f(2); // this will not be executed
f(3); // this will be executed after a second
setTimeout(function(){
  f(4); // this would be executed immediately (1.5 seconds after the first)
}, 1500);

【讨论】:

    猜你喜欢
    • 2014-09-02
    • 2021-10-06
    • 2021-09-22
    • 2015-07-07
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    相关资源
    最近更新 更多