Javascriptファイルで定義されているすべての関数を返す 質問する

Javascriptファイルで定義されているすべての関数を返す 質問する

次のスクリプトでは、スクリプトのすべての関数を配列として返す関数をどのように記述すればよいでしょうか。スクリプトで定義されているすべての関数の概要を印刷できるように、スクリプトで定義されている関数の配列を返したいと思います。

    function getAllFunctions(){ //this is the function I'm trying to write
        //return all the functions that are defined in the script where this
        //function is defined.
        //In this case, it would return this array of functions [foo, bar, baz,
        //getAllFunctions], since these are the functions that are defined in this
        //script.
    }

    function foo(){
        //method body goes here
    }

    function bar(){
        //method body goes here
    }

    function baz(){
        //method body goes here
    }

ベストアンサー1

これは、ドキュメントで定義されているすべての関数を返す関数です。この関数は、すべてのオブジェクト/要素/関数を反復処理し、タイプが「関数」であるものだけを表示します。

function getAllFunctions(){ 
        var allfunctions=[];
          for ( var i in window) {
        if((typeof window[i]).toString()=="function"){
            allfunctions.push(window[i].name);
          }
       }
    }

​こちらはjsFiddle の動作デモ

最後に関数を追加すると、このスニペットはgetAllFunctions().slice(48, -4)Vivaldi のユーザー定義関数を返すだけになります。

おすすめ記事