title: JavaScript give called function access to calling function variables
body: <p>If I define an inner function inside a function, the inner function has access to the outer function's variables. If I want this inner function to be reusable and define it outside the outer function, the inner function now loses access to the outer function variables. How do I make this new reusable inner function have access to outside function variables, without passing those variables in as parameters?</p>
  
  <pre><code>        function a () {
  
          var x = [[1,2,3], [1,2,3], [1,2,3]];
  
          var keys = Object.keys(x[0]);
  
          for (var i = 0; i &lt; x.length; i++) {
              angular.forEach(keys, loop);
          }
  
          }
  
          function loop (key) {
              console.log(key, i);//i is undefined here
          }
          a();
  </code></pre>
  
  <p>Specifically, is there some way without 1) assigning variables to this, 2) without passing in variables as parameters, and 3) without creating global variables?     </p>
  
  <p>Edit: It seems there is no way to do this. But if I try another approach, to have the reusable function return a new function, I also do not have access to the inner scope. Why is this, and is there some way to make this work?</p>
  
  <pre><code>        function a () {
  
          var x = [[1,2,3], [1,2,3], [1,2,3]];
  
          var keys = Object.keys(x[0]);
          var myloop = loop();
  
          for (var i = 0; i &lt; x.length; i++) {
              angular.forEach(keys, myloop);
          }
  
          }
  
          function loop (key) {
              return function(key) {
                   console.log(key, i);//i is undefined here
              };
          }
          a();
  </code></pre>