I’m using Node.js and am creating some models for my different objects. This is a simplified version of what they look like at the moment.
var Foo = module.exports = function () {
var values = { type: 'foo', prop1: '', prop2: '' };
function model() {}
model.init = function(val) {
_.extend(values, val);
return model;
}
model.store = function(cb) {
db.insert(values.type, values, cb);
}
model.prop1 = function(val) {
if(!arguments.length) return values.prop1;
values.prop1 = val;
return model;
}
return model;
}
Then I can do:
var foo = Foo();
foo.init({prop1: 'a', prop2: 'b'}).store(function(err) { ... });
A lot of the functions, like model.init and model.store are going to be identical for every model, but they depend on local variables in the closure like values.
Is there a way to pull these functions into a base class that I can then extend each of models with instead of duplicating all of this code? I would like to end up with something like this, but I’m not sure what the base class should look like or the right way to use it to extend Foo.
var Foo = module.exports = function () {
var values = { type: 'foo', prop1: '', prop2: '' };
function model() { this.extend(base); }
model.prop1 = function(val) {
if(!arguments.length) return values.prop1;
values.prop1 = val;
return model;
}
return model;
}
Yes you could do something like this;
model.js
then the usage would be similar to;
If you need to extend the constructor