动态委派继承

时间:2016-09-19 14:37:00

标签: javascript

假设我有构造函数FooBarQux。如何创建一个具有委托链(使用那些构造函数)的新对象,我会动态地选择它?

例如,对象将具有委托链Foo - > Bar
另一个对象将具有链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');
  }
}

对象fooBar可以拨打foo()bar()。另一个对象fooQux可以调用foo()qux()。等

2 个答案:

答案 0 :(得分:6)

您可以将这些构造函数用作mixins:

var fooBar = {};
Bar.call(fooBar);
Foo.call(fooBar);

var fooQux = {};
Qux.call(fooQux);
Foo.call(fooQux);

但您可能希望将它们编写为装饰器,甚至可能返回修改后的对象,而不是构造函数,因为无论如何都无法使用它们的原型。所以更方便的模式是

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;
}

以便您可以像

一样使用它们
var fooBar = withFoo(withBar({}));
var fooQux = withFoo(withQux({}));

答案 1 :(得分:0)

如评论所述,不确定但我猜您可以尝试instanceof

想法是,有一个包装函数将检查构造函数并将调用必要的函数。替代方案可以是在所有类函数中具有相同的名称函数。所以你只需要致电object.functionName()

Sample Fiddle



function Foo() {
  this.foo = function() {
    console.log('foo');
  }
}

function Bar() {
  this.bar = function() {
    console.log('bar');
  }
}

function Qux() {
  this.qux = function() {
    console.log('qux');
  }
}

function createObj() {
  var index = Math.floor(Math.random() * 10) % 3;
  switch (index) {
    case 0: return new Foo();
    case 1: return new Bar();
    case 2: return new Qux();
  }
}

function checkObjectAndCallFunc(obj) {
  if (obj instanceof Foo) {
    delete obj;
    obj.foo();
  } else if (obj instanceof Bar) {
    delete obj;
    obj.bar();
  } else if (obj instanceof Qux) {
    delete obj;
    obj.qux();
  }
}

function test(obj) {
  obj = createObj();
  checkObjectAndCallFunc(obj);
  if (count < 10) initTimeout()
}
var count = 0;
var obj = {};

function initTimeout() {
  count++;
  setTimeout(test.bind(null, obj), 1000);
}
initTimeout()
&#13;
&#13;
&#13;