2017-01-17 3 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

:だから、おそらくこれは、window名前を(同じオブジェクトが)使用して、なしあなたが要求したものに最も近いものです](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はES6の使用でES7、次のとおりです。

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

かで

ES2015またはそれ以前の使用:

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

あなたもObject.keys持っていない場合は、あきらめます。 ..))

0

私は取得しようとしているところを理解しています。おそらく[スコープ内のすべての変数を取得するの複製を

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

関連する問題