I get after calling the function __self.getJSonData () - empty object {} . Maybe someone will find an error / problem.

Here is the code

(function() { function Calculator() { var __self = this; this.render = function() { console.log(__self.getJSonData()); } } //Получить данные из JSON Calculator.prototype.getJSonData = function() { var ajax = new XMLHttpRequest(); var url = 'data.json'; var self = this; var data = {}; ajax.onreadystatechange = function() { if (ajax.readyState == 4 && ajax.status == 200) { returnData(ajax.responseText); } }; ajax.open("GET", url, true); ajax.send(); function returnData(json) { data = JSON.parse(json); console.log(data); } return data; }; window.calculator = new Calculator(); calculator.render(); })(); 

Reported as a duplicate by Grundy , user207618, Pavel Mayorov , cheops , aleksandr barakin 12 Aug '16 at 5:38 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • getJSonData returned much earlier than the asynchronous ajax.onreadystatechange , within which you assign data non-empty value - Igor
  • But how can this be implemented differently? - Victor-AA

1 answer 1

 (function() { function Calculator() { this.render = this.getJSonData( function(data) { console.log(data); } ); } //Получить данные из JSON Calculator.prototype.getJSonData = function(callback) { var ajax = new XMLHttpRequest(); var url = 'data.json'; var self = this; var data = {}; ajax.onreadystatechange = function() { if (ajax.readyState == 4 && ajax.status == 200) { returnData(ajax.responseText); } }; ajax.open("GET", url, true); ajax.send(); function returnData(json) { data = JSON.parse(json); if (callback) { callback(data) } } }; window.calculator = new Calculator(); calculator.render(); })();