在typescript中用装饰器,对某个class上增加一些方法。
//Decorator
export default function eventDecorator(target: EventEmitterType) {
target.prototype.on = __event.on.bind(__event)
target.prototype.off = __event.off.bind(__event)
target.prototype.remove = __event.remove.bind(__event)
target.prototype.Events = __event.Events
target.prototype.emit = function(
eventName: string,
...params: Array<string>
) {
__event.emit.call(__event, eventName, this, ...params)
}
}
//class
@eventDecorator
class Test {
constructor() {
let _this = this as any
console.log(111111111)
_this.on('aa', this.callback)
_this.emit('aa', this)
}
callback() {
console.log(this)
}
}
new Test()
这个时候直接调用this.on
IDE无法识别装饰器方法,改怎么写,不用extends
http://www.typescriptlang.org...
官方的例子就是用extends实现的,官方就是希望你用extends实现这样的需求,不要总想自己去发明一些奇奇怪怪的东西
https://github.com/Microsoft/...
根据这篇issue,typescript目前虽然可以用上面的方法添加属性方法,但不支持对添加的属性方法进行类型推导,因为typescript里使用装饰器后类的类型是不变的。。。。。
以后能不能修改页不知道