Add variable to a functions scope / closure. function equivalent of window object

前端 未结 1 1231
名媛妹妹
名媛妹妹 2020-12-12 06:20

With the following code I am able to take values out of an object and add them to the global namespace. This is defined in the expose function

function expos         


        
相关标签:
1条回答
  • 2020-12-12 06:59

    I know this problem in this case can be solved with a var map = _.map.

    That's exactly the (only) way to go.

    I want write a function that exposes more than one variable at a time.

    You should not. Have a look at my answer on the dual question Is it possible to import variables in JavaScript (node.js)?

    However, exporting variables (into a scope that you don't own) is even more complicated than importing (into your own scope). Basically, it is impossible because scopes (apart from global) are not objects that can be passed around, and be dynamically modified.

    How to solve this

    You need to modify the code of the function whose scope you want to change/extend. I can think of two ways:

    • use eval. export() will return a statement that will declare and initialise the variables:

      function export() {
          var lines = [];
          for (var p in moduletoexpose)
              lines.push("var "+p+" = require('moduletoexpose')."+p+";");
          return lines.join("\n");
      }
      
      (function() {
          eval(export(…));
          // use `map` here
      }())
      
    • Similarly, you could write a function that takes the closure, decompiles it, adds the variable declarations to the code, and uses the Function constructor to create a function from it. It might be used like

      exportTo(…, function() {
          // use `map` here
          // don't use any free variables but global ones
      })();
      

      Doesn't sound as good as the eval solution, but you might want to check out this answer for inspiration on how to write such an exportTo.

    0 讨论(0)
提交回复
热议问题