Reputation: 3756
So I'm exporting an object from one file and I'm trying to inherit all of it's methods and add
function childClass (model) {
this.model = model
}
childClass.prototype.foo1 = function(){
this.model.Something1();
}
childClass.prototype.foo2 = function(){
this.model.Something2();
}
Ideally when someone instantiates an object from childClass I would like for it to inherit all of the methods from the base model object the class is using, just so that instead of calling obj.model.function1 I could just call obj.function1.
Upvotes: 0
Views: 36
Reputation: 3042
you are actually ask how to mix the model in childclass
function childClass (model) {
Object.keys(model).forEach(function(key) {
childClass.prototype[key] = model[key].bind(model);
});
}
var m = { create: function() {console.log(this);}};
var c = new childClass(m);
c.create();
the this
context of the create method will be model, if you don't want to bind this to model, than remove bind function
Upvotes: 0
Reputation:
You may be looking for a delegation pattern, which you could implement as:
defineDelegate(delegatee, method) {
childClass.prototype[method] = function() {
var delegatee = this[delegatee];
return delegatee[method].apply(delegatee, arguments);
};
}
Now you can say
defineDelegate('model', 'Something1');
defineDelegate('model', 'Something2');
This will need to be cleaned up and generalized, but I hope you get the idea.
If for some reason you want to delegate all methods on model
:
Object.keys(modelClassPrototype)
.filter (function(k) { return typeof modelClassPrototype[k] === 'function'; })
.forEach(function(k) { defineDelegate('model', k); })
;
Upvotes: 1