0

我刚刚通读了Mike Koss 关于 JavaScript 中的面向对象编程。他简要谈到了子分类,并谈到了“另一种子分类范式”。在这个例子之后,科斯写道......

不幸的是,这种技术不允许使用instanceof 运算符来测试超类的成员资格。但是,我们还有一个额外的好处,那就是我们可以从多个超类中派生(多重继承)

...这让我思考。多重继承的想法似乎很酷!所以我有两组问题:

  1. 多重继承的想法实用吗?真的实践了吗?有什么优点或缺点吗?
  2. 我将如何覆盖instanceof运算符以将其功能扩展到多重继承?
4

2 回答 2

2

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

查看实时示例

于 2011-03-31T18:12:46.787 回答
1

John Resig 的类结构以及许多其他类结构都允许进行 instanceof 检查。

考虑重写 instanceof 并不疯狂(我实际上赞扬了你的想法,这是我会做的事情 :)),但这是不可能的。instanceof 不是一个函数,它是一个被编译器解析出来的 javascript 关键字,因此无法覆盖。

至于多重继承,没有人在实践中使用它,因为它无法跟踪。当两个父类实现相同的东西时会发生什么?哪个优先?您如何将它们与子类区分开来?

于 2011-03-31T17:50:13.463 回答