假设我想使用此API作为执行应用程序的示例:

var db = new Database('db-name'); // DB connection
var todo = new Todo(db); // New "Todo" and pass it the DB ref
// I want this API:
todo.model.create('do this', function (data) {
  console.log(data);
});

我现在有它的安装程序:
function Todo (storage) {
  this.storage = storage;
};

Todo.prototype.model = {
  create: function (task, callback) {
    // The problem is "this" is Todo.model
    // I want the "super", or Todo so I can do:
    this.storage.save(task, callback);
  }
}

因此,如果您看到注释,则问题在于this内的“model.create”显然是在引用Todo.model,但是我需要它来获取“super”。

我能想到的最好的是:
Todo.prototype.model = function () {
  var self = this;
  return {
    create: function (task, callback) {
      // The problem is "this" is Todo.model
      // I want the "super", or Todo so I can do:
      self.storage.save(task, callback);
    }
  }
}

但是这两个都不是很好。最大的问题是,我不想将所有关于model的方法都放在单个对象(第一个示例)或函数(第二个)内。我希望能够从模型def的内部将它们取出。其次,我想拥有todo.model.create API。

有没有实现这一目标的设计模式?

最佳答案

您不能将todo.model用作原型(prototype)模式,因为modeltodo的属性。

我认为您需要:

  • 一个新的Model对象,可以在其上使用原型(prototype)模型。
  • Todo构造函数中的
  • 中,创建一个Model对象。理想情况下,使用只读的“getter”函数来允许访问该模型对象,但不能将其覆盖。
  • 10-07 19:08
    查看更多