Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic delegation inheritance

Tags:

javascript

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.

like image 725
Matthew Avatar asked Sep 19 '16 14:09

Matthew


1 Answers

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({}));
like image 102
Bergi Avatar answered Sep 24 '22 20:09

Bergi