0

我有以下从这个 StackOverflow 问题创建的函数。

我的问题是关于返回函数的参数;(callback, ms, uniqueId).

这些变量在我运行时添加到哪个范围内delayResizeEvent(func(), 500, "Unique name")

var delayResizeEvent = (function () {
    'use strict';
    var timers = {};
    return function (callback, ms, uniqueId) {
        if (!uniqueId) {
            uniqueId = "Don't call this twice without a uniqueId";
        }
        if (timers[uniqueId]) {
            clearTimeout(timers[uniqueId]);
        }
        timers[uniqueId] = setTimeout(callback, ms);
    };
})();

我很感激我的措辞可能有点不对劲。如果是这样,请改进我的问题。

4

4 回答 4

1

Looks like a javascript closure, in which the parameters in delayResizeEvent(func(), 500, "Unique name") are called from the outside function (delayResizedEvent), but the inside function (return function() which is an anonymous function) can access them as well. func(), 500 and "Unique Name" are in the scope of delayResizeEvent, but because of the closure created from a function within a function, the inside function can access the outside function's variables.

More on Javascript Closures. See example #7 which has a similar format to your code.

于 2013-07-04T14:38:03.097 回答
1

In which scope are these variables added to when I run delayResizeEvent(func(), 500, "Unique name")?

A new one. When the function is called, a new variable context is instantiated. It will reference the scope of the anonymous function (which contains the timer variable) as its parent context (to where lookups continue). The scope contains the 3 variables which were declared as formal parameters: callback, ms, and uniqueId.

The passed values (ie. the result of func(), the number and the string) will be bound to them, and the function code is executed. After the function finished, the scope can be garbage-collected since nothing references it any more.

于 2013-07-04T15:54:04.670 回答
1

当我运行 delayResizeEvent(func(), 500, "Unique name") 时,这些变量被添加到哪个范围?

前 2 个参数用作 setTimeout 的参数,最后一个用于在名为 timers 的对象上添加或查找键值,该对象可用是因为 delayResizeEvent 是函数的返回值(闭包)。闭包是当一个函数返回一个值时,该函数是或包含一个或多个函数。每个返回的函数都有一个特殊的环境,因此您可以访问在返回它/它们的函数体中声明的变量。

传递的变量和timers变量的作用域只在函数体内。

你可以在这里找到更多关于闭包的信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

如果您想继续使用唯一 ID 调用此函数,那么我建议清理计时器,因为它可能会泄漏内存:

if (timers[uniqueId]) {
    clearTimeout(timers[uniqueId]);
    delete timers[uniqueId];
}
timers[uniqueId] = setTimeout(function(){
   delete timers[uniqueId];
   callback();
}, ms);
于 2013-07-04T14:49:25.557 回答
1

delayResizeEvent(func(), 500, "Unique name") is using a closure. The argument values are locally bound at function scope to function (callback, ms, uniqueId) only.

于 2013-07-04T15:34:00.420 回答