2011-02-24 10 views
46

Tengo una clase jquery dentro de una clase normal en javascript. ¿Es posible acceder a variables en el ámbito de la clase padre de una función de devolución de llamada en la clase jquery?js: acceso al alcance de la clase principal

Un ejemplo sencillo de lo que me refiero se muestra a continuación

var simpleClass = function() {  
    this.status = "pending"; 
    this.target = jqueryObject; 
    this.updateStatus = function() { 
     this.target.fadeOut("fast",function() { 
      this.status = "complete"; //this needs to update the parent class 
     }); 
    }; 
}; 

Ahora en el ejemplo anterior, la función de devolución de llamada intenta acceder al ámbito del objeto jquery. ¿hay alguna forma de acceder a la variable de estado en la clase principal?

+0

por clase u significa método o función ¿no? – Val

Respuesta

76

ajusta "este" de una variable en la función madre y luego usarlo en la función interna.

var simpleClass = function() {   
    this.status = "pending";  
    this.target = jqueryObject;  

    var parent = this; 

    this.updateStatus = function() {   
      this.jqueryObject.fadeOut("fast",function() {    
       parent.status = "complete"; //this needs to update the parent class   
      });  
     }; 
    }; 
+1

Eso no funciona padre está en el alcance de simpleClass no de el objeto jquery Lo que tiene que recordar es que el código de llamada a jQuery se llama como su propia función y tiene que ver con dónde se estableció – Barkermn01

+1

Esto funcionó bien, gracias por la ayuda – Sam

+4

@ Barkermn01 la variable es accesible por los poderes de cierres! https://developer.mozilla.org/en/JavaScript/Guide/Closures – Humberto

2

Lo siento m8. Tienes que anidan la referencia abajo en los objetos, así:

var simpleClass = function() { 
    var _root = this; 
    this.status = "pending"; 
    this.target = jqueryObject; 
    this.updateStatus = function() { 
     this.root = _root; 
     _root.target.fadeOut("fast",function() { 
      this.status = "complete"; //this needs to update the parent class 
     }); 
    }; 
}; 

notificación del var _root

+0

ok me veo ahora que podría haber usado 'this.root.target' en lugar de' _root.target' pero es lo mismo, por lo que no importa :) – Tokimon

0

Puede MANTENER estado usando variables de cerradura:

function simpleClass() { 
    var _state = { status: "pending", target: jqueryObject; } 

    this.updateStatus = function() { 
     this.target.fadeOut("fast",function() { 
     _state.status = "complete"; //this needs to update the parent class 
     }); 
    } 
} 

// Later... 
var classInstance = new simpleClass(); 
0

intente esto:

var sc = (function(scc){ 

    scc = {}; 

    scc.target = jQueryObject; 


    scc.stt = "stt init"; 

    scc.updateStatus = function(){ 
     var elem = this; 

     this.target.click(function(){ 
      elem.stt= "stt change"; 
      console.log(elem.stt); 
     }) 

    } 

    return scc; 


}(sc || {})); 

también puede definir su objeto de destino como variable privada

27

voy a publicar este responda a esta vieja pregunta de todos modos ya que nadie ha publicado esto antes.

Puede usar el método bind en sus llamadas a funciones para definir el alcance al que pertenece this.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Normaly cada vez que crear un método - this pertenece al ámbito actual de la función. Las variables de scope2 no pueden ver variables desde scope1.

p. Ej.

function(){ 
    // scope 1 
    this.baz = 'foo'; 

    function(){ 
     // scope 2 
     this.baz // not defined 
    }; 
}; 

con el método bind puede definir el alcance de this dentro de la función. Así, utilizando .bind(this) que estás diciendo la función llamada de que su propio ámbito de this se refiere al ámbito de la función madre, como:

function(){ 
    // scope 1 
    this.baz = 'foo'; 

    function(){ 
     // scope 1 
     this.baz // foo 
    }.bind(this); 
}; 

por lo que en su caso, esto sería un ejemplo usando el método bind

var simpleClass = function() {  
    this.status = "pending"; 
    this.target = jqueryObject; 
    this.updateStatus = function() { 
     this.target.fadeOut("fast",function() { 
      this.status = "complete"; //this needs to update the parent class 
     }.bind(this)); 
    }.bind(this); 
}; 
+0

¡gracias increíbles que ayudaron! – cwirz

+0

Esto soluciona perfectamente el problema al intentar acceder a un objeto 'this' anidado dentro de una clase de JavaScript. ¡Gracias! – KKlouzal

+0

Funciona perfectamente, pero Sublime Text lo odia por alguna razón ... – Treycos

1

al establecer "este" a una variable se puede acceder fácilmente.Al igual que:

$("#ImageFile").change(function (e) { 
    var image, file; 
    var Parent=this; 
    if ((file = Parent.files[0])) { 
     var sFileExtension = file.name.split('.')[file.name.split('.').length - 1]; 

     if (sFileExtension === "jpg" || sFileExtension === "jpeg" || sFileExtension === "bmp" || sFileExtension === "png" || sFileExtension === "gif") { 
      var reader = new FileReader(); 

      reader.onload = function (e) { 
       alert(Parent.files[0].name); 
      }; 
      reader.readAsDataURL(Parent.files[0]); 
     } 
     else { alert('Wrong file selected. Only jpg, jpeg, bmp, png and gif files are allowed.'); } 
    } 
}) 
1

Con función de flecha

var simpleClass = function() {  
    this.status = "pending"; 
    this.target = jqueryObject; 
    this.updateStatus = function() { 
     this.target.fadeOut("fast",() => { // notice the syntax here 
      this.status = "complete"; // no change required here 
     }); 
    }; 
}; 

Clase Sintaxis

class simpleClass { 

    constructor() { 
     this.status = 'pending'; 
     this.target = jqueryObject; 
    } 

    updateStatus() { 
     this.target.faceOut('fast',() => { 
      this.status = "complete"; 
     }); 
    } 
} 

var s = new simpleClass(); 
s.updateStatus(); 

código descrito sólo funciona en los navegadores modernos.

Cuestiones relacionadas