Search code examples
javascriptprototype

How to get prototype properties


i write this code but i don`t now why my console.log give me undefined and how can i get value of prototype properties or functions

(function() {

    function Users() {}
    Users.prototype.getUser = function() {
      $.getJSON('/usersList/users.json', function(request) {
        Users.prototype.allUsers = request.users;
      });
    }

    var users = new Users();
    users.getUsers();

    console.log(users.allUsers);
  }
  ())

What i wont to achieve is to have this user list as my object property like User.allUsers in some array. Thanks


Solution

  • This is because $.getJSON is asynchronous.

    When you create an object from User prototype, $.getJSON has to call its callback yet.

    In the other hand, you're trying to simulate global variables adding data properties to a given prototype. This is a bad practice and, at the end of the day, you've already realized that you got stuck on this approach.

    What you need an initialization code executed whenever the site or app is started so those allUsers are called once and injected everywhere:

    const initApp = () =>  Promise.all([
        $.getJSON("/someData/users.json")
        // other comma-separated async functions which return promises
    ])
    
    initApp().then(([allUsers, otherData, yetAnotherData]) => {
    
        callSomeFunctionWhichRequiresAllUsers(allUsers)
    })