0

I have a function in costructor to load some data. Can I use constructor to initialize itself on success load?

function User(userId, fullName = '', email = '') {
  this.userId = iserId;
  this.fullName = fullName;
  this.fullName = email;

  this.loadUser = function(url) {
    $.ajax({
      url: url,
      type: 'GET',
      dataType: 'json',
      data: {
        userId: this.userId
      },
      success: function(data) {
        this(this.userId, data.user.fullName, data.user.email); //???????????????
      },
    });
  }
}

let user = new User(123);
user.loadUser('myUrl');
adiga
  • 34,372
  • 9
  • 61
  • 83
  • No, but you can extract those initialization statements to a method, and call it from both the constructor and the `loadUser()` method... – Usagi Miyamoto Dec 23 '20 at 08:12
  • No, this doesn't work. See [Is it bad practice to have a constructor function return a Promise?](https://stackoverflow.com/q/24398699/1048572). Write a *static* method `User.load` that returns a promise for a new instance. – Bergi Dec 23 '20 at 11:14
  • @Bergi My constructor doesn't return promise. It's AJAX function, that can be called after instantiating of object. – Mikhail Kulikov Dec 23 '20 at 11:49
  • @MikhailKulikov `$.ajax` does return a promise, even if `loadUser` doesn't yet `return` that (it should). But regardless, you want to do an asynchronous call in your constructor to initialise the instance (whether with promises or plain callbacks), and that is what you should not do. No good reason to instantiate an empty object and later load data - do it the other way round: load the data first, then use it to instantiate a complete object. – Bergi Dec 23 '20 at 14:49
  • @Bergi Yes, you right about $.ajax and asynchronous call. In real app I use pubsub callbacks to handle it. The question is not about it. – Mikhail Kulikov Dec 24 '20 at 05:50
  • Doesn't matter. Same advice for *any* asynchronous initialisation. – Bergi Dec 24 '20 at 08:55

0 Answers0