对于下面的脚本,我怎么能写返回所有的脚本的功能,作为阵列的功能? 我想返回的脚本中定义的功能的阵列,这样我可以打印在脚本中定义的每个功能的摘要。
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
这里是一个将返回文档中定义的所有功能的功能,它的作用是通过只有那些类型为“功能”的所有对象/元素/功能和显示迭代。
function getAllFunctions(){
var allfunctions=[];
for ( var i in window) {
if((typeof window[i]).toString()=="function"){
allfunctions.push(window[i].name);
}
}
}
这里是一个的jsfiddle工作演示