返回Javascript文件中定义的所有函数 [英] Return all of the functions that are defined in a Javascript file
本文介绍了返回Javascript文件中定义的所有函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于以下脚本,如何编写一个将所有脚本函数作为数组返回的函数?我想返回脚本中定义的函数数组,以便我可以打印脚本中定义的每个函数的摘要。
For the following script, how can I write a function that returns all of the script's functions as an array? I'd like to return an array of the functions defined in the script so that I can print a summary of every function that is defined in the script.
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
}
推荐答案
在伪名称空间中声明它,例如:
Declare it in a pseudo namespace, for example like this:
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
这篇关于返回Javascript文件中定义的所有函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文