关于JavaScript中的上下文的困惑

时间:2017-01-31 23:05:25

标签: javascript

我有一个关于JavaScript中的上下文的问题,我觉得很困惑(可能因为我对JavaScript / Web开发新手总体而言)。我正在调用函数initialize并将其指定为运行它的上下文,在其中我正在从input元素订阅keyup事件并将其绑定到此上下文。但是,函数搜索在窗口函数中调用,即使它是由在Filter-context中调用的函数调用的。为什么会那样?我认为在调用者上下文中会调用一个函数。

function Filter() {

    /**
     * Other objects are set to this context (Filter)
     */ 

    var search = function() {
        /// Context here is window
    }

    var initialize = function() {
        /// Context here is this (Filter)
        this.searchBox = $("#search-box");
        this.searchBox.keyup((function() {
            /// Context here is this (Filter) due to the bind()
            var newSearch = this.searchBox.val();
            var previousSearch = this.filterValues.search;

            if (newSearch !== previousSearch) {
                if (newSearch.length === 0)
                    this.filterValues.Search = null;
                else
                    this.filterValues.Search = newSearch;

                clearTimeout(this.searchTimer);
                this.searchTimer = setTimeout(search, 250);
            }
        }).bind(this));
    }

    initialize.call(this);
}

用法:

this.filter = new Filter();

1 个答案:

答案 0 :(得分:1)

我想我找到了答案:

this.searchTimer = setTimeout(search, 250);

替换为

this.searchTimer = setTimeout(search.bind(this), 250);

因为setTimeout的上下文是窗口,因此在窗口中调用了搜索。