title: How can one use the value returned from a nested function within a method, in another method?
body: <p>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 </p>
  
  <pre><code>var info = JSON.parse(xhr.responseText);
  </code></pre>
  
  <p>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. </p>
  
  <pre><code>function TestConstructor(url) {
    var newObject = {};
    this.newObject = newObject;
  </code></pre>
  
  <p>First method in the constructor function:</p>
  
  <pre><code>  newObject.load = function () {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "http://notarealurl.com/104857.json");
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) {
          var info = JSON.parse(xhr.responseText);
          return info;
        }
       };
       xhr.send();
     };
  </code></pre>
  
  <p>Second method in the constructor function:</p>
  
  <pre><code> newObject.getNames = function (info) {
     var kommuner = info.elements;
     var result = [];
     for (i = 0; i &lt; Object.keys(kommuner).length; i++) {
        result.push(Object.keys(kommuner)[i]);
        }
     return result;
   };
  
  return newObject;
  }
  </code></pre>
  
  <p>When I try to </p>
  
  <pre><code>console.log(newObject.getNames(info)); 
  </code></pre>
  
  <p>I receive error message</p>
  
  <pre><code>Uncaught TypeError: Cannot read property 'elements' of undefined
  at Object.TestConstructor.newObject.getNames 
  </code></pre>
  
  <p>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 :)</p>