2011-08-25 7 views
9

tengo esto:variable de clase Acceso JavaScript dentro de una función de clase

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

Dentro de la función onkeyup quisiera acceder select, pero sé que no es posible de inmediato. ¿Cuál es la forma apropiada de hacer esto?

+1

Trate de añadir 'this.search.select = this.select' como el tercer línea de tu función. – Blazemonger

Respuesta

6

Antes de la función onkeyup, declare una variable. Algo así como var _this = this y luego en la función de teclado, solo use _this en lugar de this.

Así que su código será algo como:

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

Es necesario crear una variable que se llevará a cabo en el ámbito de cierre de la función 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); 
     } 
    } 
} 

Al hacer esto, se asegúrese de que se haga referencia al valor adecuado, independientemente del alcance con el que se llame a la función onkeyup (generalmente el ámbito global/ventana debido a eventos).

EDITAR
En realidad, si sólo tiene que acceder select, usted debe ser capaz de hacer esto ya:

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