在类函数中访问JavaScript类变量

Ian*_*thy 12 javascript inheritance class

我有这个:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

onkeyup我希望访问的函数内部select,但我知道它不可能存在.这样做的正确方法是什么?

Edu*_*uca 9

在onkeyup函数之前,声明一个变量.有点像var _this = this然后在keyup函数中,只需使用_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);
    }
}
Run Code Online (Sandbox Code Playgroud)