Class attribute in constructor

1

I can access an attribute of the class within the scope of the constructor, however outside gives ' undefined '

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

If, for example, in the code above, I give% of the% in the parameter received and the attribute, both return the same value, but when I use the attribute in the rest of the class, I can not.

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>
    
asked by anonymous 30.10.2017 / 17:59

1 answer

0

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

To get around this in an easy way, you can save the% object of% of your instance to another variable before doing 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);
    });
  }
}
    
30.10.2017 / 18:31