Let's say I have constructor functions Foo
, Bar
and Qux
. How can I create a new object with a delegation chain (using those constructors) that I would dynamically choose on the fly ?
For example, an object would have the delegation chain Foo
-> Bar
.
Another object would have the chain Foo
-> Qux
.
function Foo() {
this.foo = function() {
console.log('foo');
}
}
function Bar() {
this.bar = function() {
console.log('bar');
}
}
function Qux() {
this.qux = function() {
console.log('qux');
}
}
An object fooBar
would be able to call foo()
and bar()
. Another object fooQux
would be able to call foo()
and qux()
. Etc.
You can use those constructors as mixins:
var fooBar = {};
Bar.call(fooBar);
Foo.call(fooBar);
var fooQux = {};
Qux.call(fooQux);
Foo.call(fooQux);
But you might want to write them as decorators, maybe even returning the modified object, not as constructors, because you cannot use their prototypes anyway. So a more convenient pattern would be
function withFoo(obj) {
obj.foo = function() {
console.log('foo');
};
return obj;
}
function withBar(obj) {
obj.bar = function() {
console.log('bar');
};
return obj;
}
function withQux(obj) {
obj.qux = function() {
console.log('qux');
};
return obj;
}
so that you can use them like
var fooBar = withFoo(withBar({}));
var fooQux = withFoo(withQux({}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With