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

How to make an object that can inherit multiple times?

本文关键字:继承 对象 何制作      更新时间:2023-09-26

我正在学习画布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.

感谢您的想法!

我终于找到了解决这个问题的方法。问题是我太盲目了,无法思考 _.extend() 在幕后做了什么。我只在据说它提供的功能下使用它。我没有想到的是,即使是原型.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;
},