2012-07-01 12 views
8

Para el siguiente script, ¿cómo puedo escribir una función que devuelva todas las funciones del script como una matriz? Me gustaría devolver una serie de funciones definidas en el script para poder imprimir un resumen de cada función definida en el script.Devuelve todas las funciones que se definen en un archivo de 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 
    } 
+0

Para aclarar, getAllFunctions() solo debería volver activar las funciones que se definen en el script en sí, y nada más. –

+0

Aclaré la pregunta original para que la pregunta ya no sea ambigua. –

+0

Ver esta publicación http://stackoverflow.com/questions/493833/list-of-global-user-defined-functions-in-javascript – anazimok

Respuesta

9

hacedlo saber en un pseudo espacio de nombres, por ejemplo como este:

var MyNamespace = function(){ 
    function getAllFunctions(){ 
     var myfunctions = []; 
     for (var l in this){ 
     if (this.hasOwnProperty(l) && 
      this[l] instanceof Function && 
      !/myfunctions/i.test(l)){ 
      myfunctions.push(this[l]); 
     } 
     } 
     return myfunctions; 
    } 

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

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

    function baz(){ 
     //method body goes here 
    } 
    return { getAllFunctions: getAllFunctions 
      ,foo: foo 
      ,bar: bar 
      ,baz: baz }; 
    }(); 
    //usage 
    var allfns = MyNamespace.getAllFunctions(); 
    //=> allfns is now an array of functions. 
    // You can run allfns[0]() for example 
+1

1 para capturar razón funciones, creo que había visto de forma similar en ** Secretos de JavaScript Ninja de John Resig ** libro – Blaster

+0

funciona, pero esto parece un poco redundante: retorno {getAllFunctions: getAllFunctions , foo foo , bar: bar , baz: baz}; ¿Es posible hacer esto sin codificar el nombre de cada función? –

+0

@Anderson: necesita una referencia a las funciones en sí, pero no tiene que ser pública. De forma alternativa, puede asignar un objeto como 'var fns = {foo: foo, bar: bar ...}' variable dentro de 'MyNamespae' y consultarlo usando' getAllFunctions'. Solo tiene que exponer 'getAllFunctions' ->' return {getAllfunctions: getAllfunctions}; ' – KooiInc

10

Aquí es una función que devolverá todas las funciones definidas en el documento, lo que hace es que itera a través de todos los objetos/elementos/funciones y muestra sólo aquellos cuyo tipo es "función".

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

Aquí es una jsFiddle working demo

+0

El problema con esto es que capturará todas las funciones definidas en los scripts anteriores que se adjuntaron a la ventana. Y es una muy mala idea tirar cosas en la ventana en primer lugar. –

+2

Añadiendo '&& window [i] .toString(). IndexOf (" native ") == - 1' a las correcciones if that. –

1

function foo(){/*SAMPLE*/} 
 
function bar(){/*SAMPLE*/} 
 
function www_WHAK_com(){/*SAMPLE*/} 
 

 
for(var i in this) { 
 
\t if((typeof this[i]).toString()=="function"&&this[i].toString().indexOf("native")==-1){ 
 
\t \t document.write('<li>'+this[i].name+"</li>") 
 
\t } 
 
}

Cuestiones relacionadas