【问题标题】:Accessing JavaScript class variable inside a class function在类函数中访问 JavaScript 类变量
【发布时间】:2011-11-03 22:18:19
【问题描述】:

我有这个:

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,但我知道这是不可能的。这样做的正确方法是什么?

【问题讨论】:

  • 尝试将this.search.select = this.select 添加为函数的第三行。

标签: javascript class inheritance


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您需要创建一个变量,该变量将保存在 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);
         }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多