使用组合的通用JavaScript模型
我目前正在开发一个Node.js应用程序,其中包含两个JavaScript模型,如下所示:使用组合的通用JavaScript模型,javascript,node.js,composition,Javascript,Node.js,Composition,我目前正在开发一个Node.js应用程序,其中包含两个JavaScript模型,如下所示: function Role(data) { this.data = data; ... } Role.prototype.save = function(...) {...} Role.findById = function(...) {...} Role.findAll = function(...) {...} 它们对大多数函数都使用相同(相似)的逻辑,但有些函数需要不同的实现来保存等等
function Role(data) {
this.data = data;
...
}
Role.prototype.save = function(...) {...}
Role.findById = function(...) {...}
Role.findAll = function(...) {...}
它们对大多数函数都使用相同(相似)的逻辑,但有些函数需要不同的实现来保存等等。所以我的想法是通过使用某种组合来重构它们。我当前的解决方案是对原型函数使用继承,对静态函数使用适配器。看起来像这样
var _adapter = new DatabaseAdapter(SCHEMA, TABLE, Role);
function Role(data) {
Model.call(this, _adapter, Role._attributes)
this.data = data;
...
}
Role._attributes = {
name: ''
}
Role.prototype.save = function(...) {...}
Role.findById = function(...) {
_adapter.findById(...);
}
Role.findAll = function(...)
{
_adapter.findAll(...)
}
但是,我对当前的解决方案并不满意,因为开发人员需要了解很多实现细节才能创建新模型。所以,我希望有人能给我一个更好的方法来解决我的问题
谢谢,
亨德里克
编辑
经过一些研究,我提出了以下解决方案:
榜样:
Role.schema = 'db-schema-name';
Role.table = 'db-table-name';
Role.attributes = { /* attributes of the model */ }
Role.prototype.save = genericSaveFunc;
Role.findById = genericFindByIdFunc;
...
一般保存:
function genericSaveFunc(...) {
if (this.id) {
// handle update
// attributes in 'this' will be updated
} else {
// handle create
// attributes in 'this' will be updated
}
}
静态泛型函数findById:
function genericFindByIdFunc(...) {
/* use this.schema && this.table to create correct SELECT statement */
}
模型创建可以封装到工厂函数中。此解决方案的优点在于简单地创建具有不同功能的新模型(例如,仅向模型添加
save
和findById
)。但我不知道依赖泛型函数的调用上下文是否是个好主意 因为您使用的是基于原型的语言。没有必要尝试进行类继承。看一看,它将使您以JavaScript的方式进行合成变得非常容易:)感谢您将我引向stampit,从而也引向Eric Elliott关于合成的帖子,但我想提出一个简单的解决方案,而不必使用其他库。