返回在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 }
声明它在一个伪命名空间,例如像这样:
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
这是一个函数,它将返回文档中定义的所有函数,它遍历所有的对象/元素/函数,只显示那些types为“函数”的函数。
function getAllFunctions(){ var allfunctions=[]; for ( var i in window) { if((typeof window[i]).toString()=="function"){ allfunctions.push(window[i].name); } } }
这是一个jsFiddle工作演示
function foo(){/*SAMPLE*/} function bar(){/*SAMPLE*/} function www_WHAK_com(){/*SAMPLE*/} for(var i in this) { if((typeof this[i]).toString()=="function"&&this[i].toString().indexOf("native")==-1){ document.write('<li>'+this[i].name+"</li>") } }