2017-01-31 49 views
0

我有一個關於JavaScript中的上下文的問題,我覺得很困惑(可能因爲我是JavaScript/Web開發的新手)。我正在調用函數initialize並將其指定爲要在其中運行的上下文,其中我正在從input元素訂閱keyup事件並將其綁定到此上下文。然而,函數搜索在窗口函數中被調用,即使它被在Filter-context中調用的函數調用。這是爲什麼?我認爲一個函數會在invokers上下文中調用。有關JavaScript中上下文的混淆

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(); 
+0

等等,我想我知道爲什麼!它是駐留在調用搜索的窗口內的計時器。這就是它! – Alex

+0

是的,就是這樣。您的代碼片段似乎意味着「搜索」本意是在「窗口」的上下文中。 –

+0

當然。處理JavaScript內的上下文是一個令人畏懼的過程。 – Alex

回答

1

我想我找到了答案:

this.searchTimer = setTimeout(search, 250); 

被替換

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

以來的setTimeout的背景是窗口,從而導致搜索了在窗口中調用。