簡體   English   中英

在類函數中訪問JavaScript類變量

[英]Accessing JavaScript class variable inside a class function

我有這個:

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 ,但我知道它不可能存在。 這樣做的正確方法是什么?

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

您需要創建一個變量,該變量將保存在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);
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM