关于组合与继承在线有很多信息,但我还没有找到适合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) 根据各种来源(2ality,esdiscuss),应该能够将mixins添加到类中:
编辑发现类方法不可枚举,因此无法工作.编辑了下面的代码,但仍然没有快乐
class CartoonCharacter {
constructor(author) {
this.author = author;
}
drawnBy() {
console.log("drawn by", this.author);
}
}
// THIS CANNOT WORK
// class methods are not enumerable
// class Human {
// haveFun() {
// console.log("drinking beer");
// }
// }
let Human = Object.create({}, {
haveFun: {
enumerable: true,
value: function () {
console.log("drinking beer");
}
}
});
class Simpson extends Object.assign(CartoonCharacter, Human) {
constructor(author) {
super(author);
}
}
let homer = new …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) 我正在组织一个小型企业应用程序,但希望尽可能干.结果,我一直在关注mixin库.
我遇到了这个库并认为这可能是一个不错的选择,因为它允许你在运行时混合进出.此外,我可以只有一个基类(BaseView),只是混合它.
问题
javascript ×4
composition ×3
mixins ×3
closures ×1
delegation ×1
dry ×1
ecmascript-6 ×1
inheritance ×1
oop ×1
traits ×1