Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

280
Visualizações
js: accessing scope of parent class

I have a jquery class within a normal class in javascript. Is it possible to access variables in the scope of the parent class from a callback function in the jquery class?

A simple example of what I mean is shown below

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

Now in the above example, the callback function tries to access the scope of the jquery object. is there any way to access the status variable in the parent class?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You set "this" to a variable in the parent function and then use it in the inner function.

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 Relatório

0

I will post this answer to this old question anyway as no one yet posted this before.

You can use the bind method on your function calls to define the scope which this belongs to.

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

Normaly everytime you create a method - this belongs to the current scope of the function. Variables from scope2 can't see variables from scope1.

e.g.

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

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

with the bind method you can define the scope from this inside the function. So using .bind(this) you're telling the called function that their own scope from this is referred to the scope of the parent function, like:

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

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

so in your case, this would be an example using the bind method

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 Relatório

0

Use an Arrow Function

An arrow function does not have it's own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope they end up finding this from its enclosing scope.

Normal function syntax

function(param1, param2) {}

Arrow function syntax

(param1, param2) => {}

Usage

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

Using an Arrow function within a ECMAScript 2015 Class

class simpleClass {

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

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

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

Described code works only in modern browsers.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda