【问题标题】:How to make an object that can inherit multiple times?如何制作一个可以多次继承的对象?
【发布时间】:2013-09-05 19:28:45
【问题描述】:

我正在学习画布 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() 的逻辑。它贯穿对象而不能够维护原型链。它创建了一个全新的对象,忘记了它的链的所有内容。
  • 如果其他人有同样的问题,添加了一个答案。 :)

标签: javascript oop inheritance


【解决方案1】:

我终于想出了解决这个问题的方法。问题是我太盲目去想 _.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;
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多