I just started with creating custom objects in javascript. I want to set this.someObjVar using code below, but something wrong in my approach. Maybe async response uses it’s own scope or thread.
// The code below used like:
someClass = new extfoo.SomeClass();
someClass.loadArrFromFile();
// this will be called far later after async returns
someClass.showSomeObjVar();
extfoo.js
=========
var extfoo = {};
extfoo.SomeClass = function() {
this.someObjVar = [];
this.showSomeObjVar = extfoo.showSomeObjVar;
this.loadArrFromFile = extfoo.loadArrFromFile;
};
// Bad results here
extfoo.showSomeObjVar = function() {
// results '0'
console.log('showSomeObjVar: ' + this.someObjVar.length);
};
// Async array population
extfoo.loadArrFromFile = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
this.someObjVar = xhr.responseText.split('\r\n')
// results '23' elements
console.log("someObjVar length: "+this.someObjVar.length);
}
}
// request code ...
};
Are you certain that
this.someObjVaris referencingextfoo?There’s a chance that the
thisobject in theextfoo.loadArrFromFilefunction is referencing the function itself (xhr.onreadystatechange), and not theextfooobject:There are several ways to fix this, but to test, try changing
thisin theextfoo.loadArrFromFilefunction toextfoo.Here’s how to fix it:
One last thing… is
extfoo.SomeClass.someObjVarsupposed to be different fromextfoo.someObjVar? This code will work if that’s the case, but otherwise, you’ll want to include aSomeClassin between each reference.