json - Javascript :: generate new variable in a closure and use it through an object instance -


h! have fetch json data remote file , grab values variables accessibles instance of object created "v".

with code "undefined"

(i'm trying minimize as possible antipatterns)

var func = function (url) {      this.url = url; };  func.prototype.fetch = function () {      // fetching json content     var res = new xmlhttprequest();     res.open('get', this.url, true);     res.onreadystatechange = function () {          if (res.readystate == 4) {             if (res.status == 200) {                  // object want access outside                 var obj = json.parse(res.responsetext);                 this.ip = obj.ip;             }         }         res.send(null);     }; };  var v = new func("http://ip.jsontest.com/?callback=showmyip"); v.fetch();  //now "undefined" console.log("ip " + v.ip); 

i hope i've been clear. me please?

thanks in advance.

the problem res.open asynchronous call. not data immediately. execution reach console.log("ip " + v.ip); before onreadystatechange code executed. can check inserting console.log or using breakpoints. need rewrite code callbacks:

var func = function (url) {      this.url = url; };  func.prototype.fetch = function (onready) {      // fetching json content     var res = new xmlhttprequest();     res.open('get', this.url, true);     var = this;     res.onreadystatechange = function () {         if (res.readystate == 4) {             if (res.status == 200) {                  // object want access outside                 var obj = json.parse(res.responsetext);                 that.ip = obj.ip;                 onready();             }         }                 };     res.send(null); };  var v = new func("http://ip.jsontest.com/"); v.fetch(function () {     console.log("ip " + v.ip); }); 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -