Class attribute in constructor

Asked

Viewed 33 times

1

I can access a class attribute within the constructor scope, but outside gives 'Undefined'

constructor(errorAlert){
  this._errorAlert = errorAlert;
}

If, for example, in the code above, I give console.log() in the received parameter and attribute, both return the same value, but when I use the attribute in the rest of the class, I cannot.

class Controller{
  constructor(errorAlert){
    this._errorAlert = errorAlert;
  }
  login(login, senha){
    let $ = new Serv();
    $.ajax({
      'url': '/login',
      'type': 'post',
      'responseType': 'json',
      'data': 'login='+login+'&senha='+senha
    }).then(function(resolve){
      let datas = resolve;
      if(datas['loginStatus'] == 1){
        window.location = base_url;
      }else{
          console.log(this._erroAlert);
          view.viewErrorMessage("Usuário ou senha incorreto", this._errorAlert);
      }
    }).catch(function(reject){
      console.log(reject);
    });
  }
}

The code works perfectly, my only problem is that of the scope of the same attribute.

Error:

TypeError: Cannot read property '_erroAlert' of undefined
    at Controller.js:19
    at <anonymous>
  • You can put the complete code in the question, including the error message that appears on console?

  • Thanks Tom Melo! Solve, but only so if I capture the DOM element inside the constructor, but I want to pass by parameter, advises something?

1 answer

0


The problem is that when you perform an anonymous function within your class, the reference to this is no longer for your object, but for the object of the AJAX request defined by $.ajax jQuery. That is, when you do this._errorAlert you are trying to access the attribute _errorAlert of your request, which does not exist.

To get around this easily, you can save the object this of its instance in another variable before making the asynchronous request:

const self = this;

And within the anonymous function, do:

console.log(slef._erroAlert);

Getting something like:

class Controller{
  constructor(errorAlert){
    this._errorAlert = errorAlert;
  }
  login(login, senha){
    let $ = new Serv();
    const self = this;    // Linha adicionada
    $.ajax({
      'url': '/login',
      'type': 'post',
      'responseType': 'json',
      'data': 'login='+login+'&senha='+senha
    }).then(function(resolve){
      let datas = resolve;
      if(datas['loginStatus'] == 1){
        window.location = base_url;
      }else{
          console.log(self._erroAlert);    // Linha modificada
          view.viewErrorMessage("Usuário ou senha incorreto", self._errorAlert);    // Linha modificada
      }
    }).catch(function(reject){
      console.log(reject);
    });
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.