【问题标题】:Programatically adding methods from an object以编程方式从对象添加方法
【发布时间】:2017-03-05 03:31:12
【问题描述】:

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

【问题讨论】:

  • 使用var func = new Function(argNames,functionBody);在MDN上查找
  • 这仍然有点像使用eval 但好吧,我接受。

标签: javascript node.js loops syntax nested-loops


【解决方案1】:

如果您只是询问在给定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])());
    }
});

【讨论】:

  • 太棒了!我做了类似的事情: for(var task in tasks){API.prototype[task]=function(){ this.runTasks(new tasks[task]); }; }` 但它给了我错误的上下文,只是给了我它处理的最后一个项目。
  • @TeeraMusic - 在现代 JS 引擎中,您可以使用 let 而不是 varfor (let task in tasks) {....},因为 letfor 循环中为每个循环的迭代,所以它本来是正确的。但是,由于我使用了.forEach(),因此每次迭代都有单独的函数上下文,所以我的解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
相关资源
最近更新 更多