在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ Typescript裝飾器問題

Typescript裝飾器問題

在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()

這個時候直接調(diào)用this.on IDE無法識別裝飾器方法,改怎么寫,不用extends

回答
編輯回答
浪婳

http://www.typescriptlang.org...

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    return class extends constructor {
        newProperty = "new property";
        hello = "override";
    }
}

@classDecorator
class Greeter {
    property = "property";
    hello: string;
    constructor(m: string) {
        this.hello = m;
    }
}

console.log(new Greeter("world"));

官方的例子就是用extends實現(xiàn)的,官方就是希望你用extends實現(xiàn)這樣的需求,不要總想自己去發(fā)明一些奇奇怪怪的東西

2018年5月25日 08:30