如何制作一个可以多次继承的对象?

时间:2013-09-05 19:28:46

标签: javascript oop inheritance

我正在学习画布API,并希望制作一个简单的物理引擎。在今年夏天使用Backbone.js之后,我受到了他们在JS中的OO方法的启发。

知道我要解决的问题,我将提出我的解决方案,但如果你认为你有更好的方法来解决这个问题,请说出来。

// Obj is a general object that can be basically anything. (Ball, rock, ground plane)
var Obj = Extendable.extend(
    position : [0, 0], // Coordinates
    velocity : [0, 0], // Vector,
    acceleration : [0, 0], // Vector
    shape : (Shape)
);

var Ball = Obj.extend(
    shape : (Shape)
);

var ball1 = new Ball();
var ball2 = new Ball(initializer);

目标是在调用new Object();之前能够扩展多次,如果有可能还有多重继承,那就太棒了。

现在我想出了这个:

var Extendable = {
    extend : function(methods) {
        var f = function() {
            if (this.init) this.init.apply(arguments);
        };

        f.prototype = Object.create(_.extend({}, this.prototype, methods));
        f.extend = this.extend;

        return f;
    }
};

//The problem is that this only allows the use of .extend() one time...
EDIT: Now half way working.

感谢您的想法!

1 个答案:

答案 0 :(得分:0)

我终于找到了解决这个问题的方法。问题是我太盲目无法思考_.extend()在幕后做什么。我只使用了它所说的功能。我没想到的是,甚至Prototype.js也无法将原型链与对象神奇地合并。 (而且他们也从来没有声称这个。他们声称它可以合并对象。)

因此,只需进行一些小改动即可使其发挥作用:

extend : function(methods) {
    // Define a constructor that will be available on all "classes".
    var f = function() {
        if (this.init) this.init.apply(arguments);
    };

    // Add the current prototype to the chain. (Added in "methods"-argument in a previous extend.
    // Then we're going to add the new methods to the prototype.
    f.prototype = _.extend(Object.create(this.prototype || {}), methods);
    // Add the .extend() on the object to allow further inheritance.
    f.extend = this.extend;

    return f;
},