我正在用 JavaScript 实现动态函数映射机制。
这是我的代码:
class FunctionMapper {
constructor() {
this.functions = {};
}
register(name, func) {
this.functions[name] = func;
}
invoke(name, ...args) {
const func = this.functions[name];
if (func) {
return func(...args);
} else {
return null;
}
}
listFunctions() {
return Object.keys(this.functions);
}
}
我的代码哪里缺少?
目标:目标是创建一个系统,允许以不同名称注册函数,然后使用注册的名称动态调用这些函数。
解决方案:
如果未找到请求的函数,则调用方法会抛出错误,这可确保用户了解未注册的函数名称的任何问题。
class FunctionMapper {
constructor() {
this.functions = {};
}
register(name, func) {
this.functions[name] = func;
}
invoke(name, ...args) {
const func = this.functions[name];
if (func) {
return func(...args);
} else {
throw new Error(`Function '${name}' not found.`);
}
}
listFunctions() {
return Object.keys(this.functions);
}
}