2011-08-25 110 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); 
    } 
}