如何制作可以多次继承的对象
How to make an object that can inherit multiple times?
我正在学习画布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;
},
相关文章:
- JavaScript对象不是从原型链继承的
- JavaScript对象继承问题
- 类中对象的奇怪问题(John Resig简单继承)
- 继承对象并将变量传递给它,javascript
- 继承对象.遍历所有对象
- 调用本机原型方法时扩展或继承对象原型
- 继承对象的最佳做法
- 从继承对象的函数调用原型的方法
- CoffeeScript类-循环遍历继承对象的数组
- 通过原型继承对象
- 在Javascript中继承对象的值
- 为什么不通过原型链继承对象方法?
- 原型继承对象的多个实例
- Javascript中继承对象的两种不同(?)方法
- 继承对象的变化反映到父对象
- Angularjs, JavaEE和http请求继承对象
- 继承对象
- 具有继承对象参数的Jquery AutoComplete
- 用nodejs封装继承对象的属性
- 如何在javascript的构造函数中重写继承对象的属性?