0

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jelena K
  • 3
  • 2
  • 3
    `Quiz` != `Users`. Please fix that first. – Bergi Oct 16 '17 at 20:53
  • 1
    Why would you want to make `allUsers` a prototype property? Is it really shared by all instances of the class? If yes, why is `getUsers` an instance method? – Bergi Oct 16 '17 at 20:54
  • 1
    And finally, `getJSON` is **asynchronous**. [It won't set the property until later (or never in case of an error)](https://stackoverflow.com/q/23667086/1048572), that's why it's still `undefined` when you access it. – Bergi Oct 16 '17 at 20:55

1 Answers1

0

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)
})
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • Thanks for this answer but is there any simple solution for this. I just want to use this json data in all my functions – Jelena K Oct 16 '17 at 21:02
  • @JelenaK No problem. Sorry, there's no other way. Well, there're variants of the same approach, but at the end of the day, asynchronous code implies working with callbacks or promises. – Matías Fidemraizer Oct 16 '17 at 21:18
  • sorry for bothering you but what is callback approach – Jelena K Oct 16 '17 at 21:38