【发布时间】:2019-02-28 03:18:13
【问题描述】:
从 Mootools 切换到 EcmaScript 类时,我需要向类添加一些预构建的功能。喜欢活动...
Mootools 为此在 Class 中使用 Implements 参数。
var Widget = new Class({
Implements: Events,
initialize: function(element){
// ...
},
complete: function(){
this.fireEvent('complete');
}
});
在上面,Implements 向类添加了一些方法。
网上有很多 mixin 方法可以做到这一点。但最后我感到困惑。为什么我们不简单地扩展 Events 类,而是使用更复杂的 mixin 应用程序。
我正在寻找干燥且易于重复使用的东西。喜欢这个;
class BaseAnimal {
//...
}
/* Events Mixin */
var Events={
//...
}
/* Options Mixin */
var Options={
//...
}
/* Extend base and add mixins */
class Parrot extends myMixinFuction(BaseAnimal,Events,Options){
//...
}
/* No Base. Only add mixin */
class Cat extends myMixinFuction(Events){
//...
}
myMixinFuction function (...args){
//do something that adds mixins to base class.
//if no base create one empty class and add mixinis to it
//return that Class
}
【问题讨论】:
-
你可以将它们 Object.assign 到原型上.. 例如..
Object.assign(Widget.prototype, Events) -
ES6 类提供了 extends 关键字来继承父类。但这仅限于 1 个扩展名。如果你想从多个来源继承,你将不得不为原型分配新的属性。
标签: javascript mootools mixins