Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
Ian Timothy Avatar asked Aug 25 '11 17:08

Ian Timothy


2 Answers

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);
    }
}
like image 176
Eduard Luca Avatar answered Oct 20 '22 21:10

Eduard Luca


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);
     }
}
like image 28
Polaris878 Avatar answered Oct 20 '22 20:10

Polaris878