以编程方式从对象添加方法

Programatically adding methods from an object

假设我有一个使用 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 自身(所以我真的需要一些在编程上等效的东西)

如果您只是询问如何在给定 tasks 对象时以编程方式构建 API.prototype,您可以这样做:

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])());
    }
});