javascript 中的模拟多继承成为一场噩梦。
我编写了一个完整的自定义类包装器以允许动态多重继承,一个月后我放弃了它,因为它不值得。复杂性变得一发不可收拾。
而不是使用多重继承,您可以使用它的父方法扩展您的对象。
我建议您坚持使用简单的对象构造函数和原型,而不是包括外部“经典 OO”仿真器。JavaScript 非常关注原型 OO,它是一个从另一个对象继承的对象,而不是一个扩展另一个类的类。
如果你想要多重继承坚持对象组合。
警告:这_
用于简单和简洁。
function Child() {
var parent1 = new Parent1();
var parent2 = new Parent2();
// bind this to parent1 so it's got it's own internal scope
_.bindAll(parent1);
_.bindAll(parent2);
// extend this with parent1 and parent2
_.extend(this, parent1);
_.extend(this, parent2);
}
是的,你输了instanceof
检查。处理它。
更一般地,您可以扩展您想要的任何对象。
function extend(f, arr) {
// return a new function to replace f.
return function() {
// store the correct this value
var that = this;
// call original f
f.apply(this, arguments);
// for each parent call it with the original this
_.each(arr, function(v) {
v.apply(that, arguments);
});
// add f to the parent array
arr.push(f);
// store the array on the object to use with instance_of
this.__instance = arr;
}
}
function instance_of(o, klass) {
// is the klass included in the .__instance array ?
return _.include(o.__instance, klass);
}
function Child() {
// do stuff
this.method = function() { console.log("method"); return this;};
}
function Parent1() {
this.foo = function() { console.log("foo"); return this; };
}
function Parent2() {
this.bar = function() { console.log("bar"); return this;};
}
Child = extend(Child, [Parent1, Parent2]);
var c = new Child();
console.log(instance_of(c, Parent1)); // true
console.dir(c);
c.method().foo().bar();
这确实依赖于underscore.js
实现一些很好的抽象来保持示例代码的小。. 扩展,.bindAll。
查看实时示例