Accessing JavaScript class variable inside a class function

11,796

Solution 1

Before the onkeyup function, declare a variable. Something like var _this = this and then in the keyup function, just use _this instead of 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);
    }
}

Solution 2

You need to create a variable which will be held in the closure scope of the onkeyup function:

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).

EDIT
Actually, if you just need to access select, you should be able to do this already:

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

Related videos on Youtube

Ian Timothy
Author by

Ian Timothy

Updated on June 04, 2022

Comments

  • Ian Timothy
    Ian Timothy about 2 years

    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. What is the proper way to do this?

    • Blazemonger
      Blazemonger almost 13 years
      Try adding this.search.select = this.select as the third line of your function.