在list
内是否可以获取所有可用的功能 - a
,b
,c
而不使用枚举且不使用window
?
(function(){
function a() { return 1; }
function b() { return 2; }
function c() { return 3; }
function list()
{
return [a, b, c];
}
})();
答案 0 :(得分:1)
不,在当前范围内直接声明的函数不可能。
要实现这一点,您必须将函数分配给范围的某些属性,即:
(function() {
let funcs = {};
funcs.a = function() {
return 1;
}
...
function list() {
return Object.values(funcs);
}
});
注意:Object.values
是ES7,在ES6中使用:
return Object.keys(funcs).map(k => funcs[k]);
或在ES2015或更早版本中使用:
return Object.keys(funcs).map(function(k) { return funcs[k] });
如果您还没有Object.keys
,请放弃......;)
答案 1 :(得分:0)
我明白你要去哪里。所以,这可能是你最接近你要求的东西,没有使用// define a non-anonymous function in the global scope
// this function contains all the functions you need to enumerate
function non_anon() {
function a() { return 1; }
function b() { return 2; }
function c() { return 3; }
function list() { return [a, b, c]; }
// you need to return your `list` function
// i.e. the one that aggregates all the functions in this scope
return list;
}
// since in here the purpose is to access the global object,
// instead of using the `window` name, you may use `this`
for (var gobj in this) {
// from the global scope print only the objects that matter to you
switch (gobj) {
case 'non_anon':
console.info(gobj, typeof this.gobj);
console.log(
// since you need to execute the function you just found
// together with the function returned by its scope (in order to `list`)
// concatenate its name to a double pair of `()` and...
eval(gobj + '()()') // evil wins
);
break;
}
}
名称(虽然是同一个对象):
{{1}}