javascript - args.unshift(function replayOrFree(){...}) 这是一种什么技巧?
PHPz
PHPz 2017-04-10 15:22:58
0
1
798

下面这段代码中的,unshift传进了一个函数,这是一种什么技巧?

var lock = function (func) {
        var locked, queuedArgsToReplay;

        return function () {
            // Convert arguments into a real array.
            var args = Array.prototype.slice.call(arguments);
            if (locked) {
                // Keep a copy of this argument list to replay later.
                // OK to overwrite a previous value because we only replay
                // the last one.
                return queuedArgsToReplay = args;
            }
            locked = true;
            var self = this;
            args.unshift(function replayOrFree() {
                if (queuedArgsToReplay) {
                    // Other request(s) arrived while we were locked.
                    // Now that the lock is becoming available, replay
                    // the latest such request, then call back here to
                    // unlock (or replay another request that arrived
                    // while this one was in flight).
                    var replayArgs = queuedArgsToReplay;
                    queuedArgsToReplay = void 0;
                    replayArgs.unshift(replayOrFree);
                    func.apply(self, replayArgs);
                } else {
                    locked = false;
                }
            });
            func.apply(this, args);
        };
    };

下面是唯一一处调用lock函数的地方

        // Call the search method of selected strategy..
        _search: lock(function (free, strategy, term, match) {
            var self = this;
            strategy.search(term, function (data, stillSearching) {
                if (!self.dropdown.shown) {
                    self.dropdown.activate();
                    self.dropdown.setPosition(self.adapter.getCaretPosition());
                }
                if (self._clearAtNext) {
                    // The first callback in the current lock.
                    self.dropdown.clear();
                    self._clearAtNext = false;
                }
                self.dropdown.render(self._zip(data, strategy));
                if (!stillSearching) {
                    // The last callback in the current lock.
                    free();
                    self._clearAtNext = true; // Call dropdown.clear at the next time.
                }
            }, match);
        }),
PHPz
PHPz

学习是最好的投资!

répondre à tous(1)
小葫芦

unshift是往数组开头插入一个元素,即下面调用lock函数地方的free参数。
之所以往开头插入而不是在结尾append大概是因为为了保持参数的一致性吧 —— 下面的search函数的参数就是除了free之外的其他参数。
这两段代码还是挺绕的,一个返回函数的函数,然后用一个函数来创建一个函数……

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal