function api() { _self = $(this); setData('parameters', { host: $("#host").val(), aid: $("#aid").val(), uid: 876, token: $("#token").val() }); function getAid() { query ='uid='+getData('parameters').uid; $.ajax({ url: getData('parameters').host+'ajax/album.php', type: "GET", data: query, success: function(response){ getData('parameters').aid = 123; console.log(getData('parameters').aid); //123 } }); } getAid(); function setData(key, data) { _self.data(key, data); } function getData(key) { return _self.data(key); } console.log(getData('parameters').aid); //876 } 

Here I am learning to write code using classes on js, please tell me how I can change a variable in success, so that the change would be distributed to the whole class, and not just inside the success function.

There I explained in the comments, I think you understood me.

  • strictly speaking there are no classes on js. - zb '
  • By the way, why do you have $ (this) there at all? just to store data? - zb '

2 answers 2

OOP in this case there is nothing. The $ .ajax () function is executed asynchronously by default. This means that the last output is console.log(getData('parameters').aid); will display the value before it is changed . To avoid this, you can set the async: false parameter. Or, better yet, use the event model — when functions that work asynchronously raise the corresponding event upon completion, which in turn hangs the handler.

  • in this case, async: false will save me, but I still need to transfer jsonp data, it won't work there, what should I do? Can you elaborate on your second proposed option? - defender057
  • Look in the direction of .trigger () and .bind () . The logic is simple: after the completion of an asynchronous function, it raises some kind of event that can then be caught using a handler function. - Acrux

For an understanding of how to create classes in Javascript, see the article: http://en.wh-db.com/article/javascript-classes-in-javascript/

There is a very simple example, compare how to create a class in the Java language and the same class in the Javascript language.

Regarding Ajax, here's a good article: http://ru.wh-db.com/article/kak-otpravit-formu-bez-perezagruzki-stranici/