我正在尝试使用TypeScript,并且有几个函数混入,Eventable
和Settable
,我想将它们混入到一个Model
类中(假设它类似于Backbone.js模型):
function asSettable() {
this.get = function(key: string) {
return this[key];
};
this.set = function(key: string, value) {
this[key] = value;
return this;
};
}
function asEventable() {
this.on = function(name: string, callback) {
this._events = this._events || {};
this._events[name] = callback;
};
this.trigger = function(name: string) {
this._events[name].call(this);
}
}
class Model {
constructor (properties = {}) {
};
}
asSettable.call(Model.prototype);
asEventable.call(Model.prototype);
上述代码运行良好,但如果我尝试使用混入的方法之一,例如
(new Model()).set('foo', 'bar')
,它将无法编译。我可以通过以下方式解决:
- 为混入添加接口声明
- 在
Model
声明中声明虚拟的get
/set
/on
/trigger
方法