1

Is it possible inside list to get all available functions - a, b, c without their enumeration and without using window?

(function(){

    function a() { return 1; }

    function b() { return 2; }

    function c() { return 3; }

    function list()
    {
        return [a, b, c];
    }

})();
bfontaine
  • 18,169
  • 13
  • 73
  • 107
O.Prokopin
  • 11
  • 2
  • 2
    Possibly a duplicate of [Getting All Variables In Scope](http://stackoverflow.com/questions/2051678/getting-all-variables-in-scope) – apsillers Jan 17 '17 at 17:07

2 Answers2

1

No, it's not possible with functions declared directly in the current scope.

To achieve this, you would have to assign the functions to some property of the scope, i.e.:

(function() {

    let funcs = {};

    funcs.a = function() {
        return 1;
    }

    ...

    function list() {
        return Object.values(funcs);
    }
});

NB: Object.values is ES7, in ES6 use:

return Object.keys(funcs).map(k => funcs[k]);

or in ES2015 or earlier use:

return Object.keys(funcs).map(function(k) { return funcs[k] });

If you haven't even got Object.keys, give up... ;)

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

I understand where you are trying to get. So perhaps this is the closest thing to what you requested, without using the window name (the same object though):

// define a non-anonymous function in the global scope
// this function contains all the functions you need to enumerate
function non_anon() {
  function a() { return 1; }
  function b() { return 2; }
  function c() { return 3; }
  function list() { return [a, b, c]; }
  // you need to return your `list` function
  // i.e. the one that aggregates all the functions in this scope
  return list;
}

// since in here the purpose is to access the global object,
// instead of using the `window` name, you may use `this`
for (var gobj in this) {
  // from the global scope print only the objects that matter to you
  switch (gobj) {
    case 'non_anon':
      console.info(gobj, typeof this.gobj);
      console.log(
        // since you need to execute the function you just found
        // together with the function returned by its scope (in order to `list`)
        // concatenate its name to a double pair of `()` and...
        eval(gobj + '()()') // evil wins
      );
      break;
  }
}
CPHPython
  • 12,379
  • 5
  • 59
  • 71