简体   繁体   English

在类函数中访问JavaScript类变量

[英]Accessing JavaScript class variable inside a class function

I have this: 我有这个:

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

Inside of the onkeyup function I would like to access select , but I know it is not possible as is. onkeyup函数里面我想访问select ,但我知道它不可能存在。 What is the proper way to do this? 这样做的正确方法是什么?

Before the onkeyup function, declare a variable. 在onkeyup函数之前,声明一个变量。 Something like var _this = this and then in the keyup function, just use _this instead of this . var _this = this类的东西然后在keyup函数中,只需使用_this而不是this

So your code will look something like: 所以你的代码看起来像:

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

You need to create a variable which will be held in the closure scope of the onkeyup function: 您需要创建一个变量,该变量将保存在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);
        }
    }
}

By doing this, you ensure that the proper value will be referenced regardless of what scope the onkeyup function is called with (usually the global/window scope because of eventing). 通过执行此操作,您可以确保将引用正确的值,而不管调用onkeyup函数的范围(通常是因为事件而导致的全局/窗口范围)。

EDIT 编辑
Actually, if you just need to access select , you should be able to do this already: 实际上,如果你只需要访问select ,你应该可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM