假设我使用require('require-all')
tasks = {
getProfile: [constructor function]
initAll: [constructor function]
login: [constructor function]
};
如何在不使用eval
的情况下以编程方式向API添加适当的方法?
API.prototype.getProfile = function(){
this.runTask(new tasks.getProfile());
};
API.prototype.initAll = function(){
this.runTask(new tasks.initAll());
};
API.prototype.login = function(){
this.runTask(new tasks.login());
}
任务需要能够递归运行,再次调用runTask
(所以我真的需要一些程序上等效的东西)
答案 0 :(得分:1)
如果您只是询问如何在给定API.prototype
对象时以编程方式构建tasks
,则可以执行以下操作:
let tasks = {
getProfile: [constructor function]
initAll: [constructor function]
login: [constructor function]
};
// populate API.prototype based on items in tasks
Object.keys(tasks).forEach(prop => {
API.prototype[prop] = function() {
this.runTasks(new (tasks[prop])());
}
});