关于组合与继承在线有很多信息,但我还没有找到适合JavaScript的例子.使用以下代码演示继承:
function Stock( /* object with stock names and prices */ ) {
for (var company_name in arguments[0]) {
// copy the passed object into the new object created by the constructor
this[company_name] = arguments[0][company_name];
}
}
// example methods in prototype, their implementation is probably redundant for
// this question, but list() returns an array with toString() invoked; total()
// adds up the stock prices and returns them. Using ES5 feature to make
// inherited properties non-enumerable
Stock.prototype = …Run Code Online (Sandbox Code Playgroud) 作为RPG游戏后端的一部分,我希望能够对角色应用临时效果.这些效果的性质可能会有很大差异,但我想保持定义它们的方法非常简单.
我正在使用自定义事件处理作为mixin:
var EvtObject = {};
$rpg.Event.enable(EvtObject); // Add the 3 methods and set EvtObject._events = {}
Run Code Online (Sandbox Code Playgroud)
我想将Auras(临时效果)定义为具有事件处理代码的构造函数:
var MyAura = function(any, args){
this.group = "classification";
this.on( "tick", function(){} );
this.on( "remove", function(){} );
};
Run Code Online (Sandbox Code Playgroud)
然后应用为MyCharacter.addAura(new MyAura(any, args));.如您所见,我希望该this.on()函数在构造函数中可用.如果我使用mixin($rpg.Event.enable(MyAura.prototype))扩展MyAura原型,那么MyAura的每个实例都会引用_events原型中的相同对象.
我想知道以下解决方案是否是良好的做法:
Aura.create = function(Constructor)
{
Constructor.prototype = Aura.getPrototype(); // Aura specific prototype
return function()
{
var newAura = Object.create(Constructor.prototype);
$rpg.Event.enable( newAura );
Constructor.apply( newAura, arguments );
return newAura;
};
};
// Then creating new …Run Code Online (Sandbox Code Playgroud) javascript ×3
composition ×2
closures ×1
delegation ×1
inheritance ×1
mixins ×1
oop ×1
prototype ×1
traits ×1