2011-08-25 19 views
9

mam to:Dostęp JavaScript klasa zmiennej wewnątrz funkcji klasy

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

Wewnątrz funkcji onkeyup chciałbym dostęp select, ale wiem, że nie jest to możliwe, jak jest. Jaki jest właściwy sposób na zrobienie tego?

+1

spróbuj dodać 'this.search.select = this.select' jako trzecia linia twojej funkcji. – Blazemonger

Odpowiedz

6

Przed funkcją onkeyup zadeklaruj zmienną. Coś takiego jak var _this = this, a następnie w funkcji keyup, po prostu użyj _this zamiast this.

Tak Twój kod będzie wyglądać następująco:

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

Musisz utworzyć zmienną, która odbędzie się w ramach zamykającego onkeyup funkcję:

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

Dzięki temu można upewnij się, że odwołano się do właściwej wartości bez względu na zasięg wywoływany przez funkcję onkeyup (zazwyczaj zasięg globalny/zakres okna z powodu zdarzenia).

EDIT
Właściwie, jeśli wystarczy, aby uzyskać dostęp select, powinieneś być w stanie to zrobić już:

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