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

下面这段代码中的,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

学习是最好的投资!

모든 응답(1)
小葫芦

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

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!