问题 在类函数中访问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,但我知道这是不可能的。这样做的正确方法是什么?


5409
2017-08-25 17:53


起源

尝试添加 this.search.select = this.select 作为你的功能的第三行。 - Blazemonger


答案:


在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);
    }
}

8
2017-08-25 17:55





您需要创建一个将保留在闭包范围内的变量 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);
     }
}

3
2017-08-25 17:59