2011-08-25 108 views
9

內訪問JavaScript類變量我有這樣的:一類功能

function FilterSelect(select, search) { 
    this.select = select; 
    this.search = search; 
    // Get the current list options 
    this.options = this.select.options; 
    // Whenever the text of the search box changes, do this 
    this.search.onkeyup = function() { 
     // Clear the list 
     while(this.select.options.length > 0) { 
      this.select.remove(0); 
     } 
    } 
} 

裏面的onkeyup功能,我想訪問select的,但我知道的是這是不可能的。什麼是正確的方法來做到這一點?

+1

嘗試增加'this.search.select = this.select'作爲第三你的功能線。 – Blazemonger

回答

6

在onkeyup函數之前,聲明一個變量。就像var _this = this然後在鍵入功能中,只需使用_this而不是this

所以,你的代碼看起來是這樣的:

var _this = this; 
// Whenever the text of the search box changes, do this 
this.search.onkeyup = function() { 
    // Clear the list 
    while(_this.select.options.length > 0) { 
     _this.select.remove(0); 
    } 
} 
3

您需要創建將在onkeyup功能關閉範圍舉行一個變量:

function FilterSelect(select, search) { 
    var _this = this; // <-- win 
    _this.select = select; 
    _this.search = search; 

    // Get the current list options 
    _this.options = this.select.options; 

    // Whenever the text of the search box changes, do this 
    _this.search.onkeyup = function() { 
     // Clear the list 
     while(this.select.options.length > 0) { 
      _this.select.remove(0); 
     } 
    } 
} 

通過這樣做,你確保引用適當的值,而不管調用onkeyup函數的範圍(通常是由於事件造成的全局/窗口範圍)。

編輯
其實,如果你只需要訪問select,你應該能已經做到這一點:

this.search.onkeyup = function() { 
    // Clear the list 
    while(this.select.options.length > 0) { 
     select.remove(0); 
    } 
}