2017-01-17 4 views
1

Возможно ли внутри внутри list получить все функции - a, b, c без их перечисления и без использования window?Можно ли получить все определенные функции внутри другой функции?

(function(){ 

    function a() { return 1; } 

    function b() { return 2; } 

    function c() { return 3; } 

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

})(); 
+2

Возможно дубликатом [Получение всех переменных в Scope ] (http://stackoverflow.com/questions/2051678/getting-all-variables-in-scope) – apsillers

ответ

1

Нет, это невозможно с функциями, объявленными непосредственно в текущей области.

Для достижения этой цели, вы должны назначить функции для некоторого свойства сферы, а именно:

(function() { 

    let funcs = {}; 

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

    ... 

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

NB: Object.values является ES7 при использовании ES6:

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

или ES2015 или ранее использование:

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

Если вы не получили даже Object.keys, сдаваться. ..;)

0

Я понимаю, где вы пытаетесь добраться. Так что, возможно, это ближе всего к тому, что вы просили, без, используя имя window (тот же объект, хотя):

// 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; 
 
    } 
 
}