Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
js: acceso al alcance de la clase principal

Tengo una clase jquery dentro de una clase normal en javascript. ¿Es posible acceder a las variables en el ámbito de la clase principal desde una función de devolución de llamada en la clase jquery?

Un ejemplo simple de lo que quiero decir 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 alcance del objeto jquery. ¿Hay alguna forma de acceder a la variable de estado en la clase principal?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Establece "esto" en una variable en la función principal y luego lo usa 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 }); }; };
over 4 years ago · Santiago Trujillo Report

0

Publicaré esta respuesta a esta vieja pregunta de todos modos, ya que nadie ha publicado esto antes.

Puede usar el método de bind en sus llamadas de función para definir el alcance al this pertenece.

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

Normalmente, cada vez que crea un método, this pertenece al alcance actual de la función. Las variables de scope2 no pueden ver las variables de scope1.

p.ej

 function(){ // scope 1 this.baz = 'foo'; function(){ // scope 2 this.baz // not defined }; };

con el método bind puedes definir el alcance desde this dentro de la función. Entonces, al usar .bind(this) le está diciendo a la función llamada que su propio alcance de this se refiere al alcance de la función principal, como:

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

entonces, en su caso, este 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); };
over 4 years ago · Santiago Trujillo Report

0

Usar una función de flecha

Una función de flecha no tiene su propio this . Se utiliza el valor this del ámbito léxico adjunto; Las funciones de flecha siguen las reglas normales de búsqueda de variables. Entonces, mientras buscan this que no está presente en el alcance actual, terminan encontrando this desde su alcance adjunto.

Sintaxis de funciones normales

function(param1, param2) {}

Sintaxis de la función de flecha

(param1, param2) => {}

Uso

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

Uso de una función de flecha dentro de una clase ECMAScript 2015

 class simpleClass { constructor() { this.status = 'pending'; this.target = jqueryObject; } updateStatus() { this.target.faceOut('fast', () => { this.status = "complete"; }); } } const s = new simpleClass(); s.updateStatus();

El código descrito solo funciona en navegadores modernos .

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!