I am having a constructor function, which in the end should return a couple of methods. Currently I struggle to understand how I can use the value from the
var info = JSON.parse(xhr.responseText);
in the method, called getNames. It works if I combine the two methods to one, so the code itself works, only problem is to pass the variable.
function TestConstructor(url) {
var newObject = {};
this.newObject = newObject;
First method in the constructor function:
newObject.load = function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://notarealurl.com/104857.json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var info = JSON.parse(xhr.responseText);
return info;
}
};
xhr.send();
};
Second method in the constructor function:
newObject.getNames = function (info) {
var kommuner = info.elements;
var result = [];
for (i = 0; i < Object.keys(kommuner).length; i++) {
result.push(Object.keys(kommuner)[i]);
}
return result;
};
return newObject;
}
When I try to
console.log(newObject.getNames(info));
I receive error message
Uncaught TypeError: Cannot read property 'elements' of undefined
at Object.TestConstructor.newObject.getNames
Sorry if similar question has been asked earlier, I have looked at a few without understanding how it solves my problem. I have also tried to look at the callback function, but I struggle to understand how it works in my case. Any help appreciated, thanks :)