鍍金池/ 問答/HTML/ 嘗試裝飾器,遇到Reflect-metadata有關(guān)的問題

嘗試裝飾器,遇到Reflect-metadata有關(guān)的問題

clipboard.png
實際代碼如下:

class Greeter4 {
    @format("Hello, %s")
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        let formatString = getFormat(this, "greeting");
        return formatString.replace("%s", this.greeting);
    }
}




const formatMetadataKey = Symbol("format");

function format(formatString: string) {
    return Reflect.metadata(formatMetadataKey, formatString);
}

function getFormat(target: any, propertyKey: string) {
    return Reflect.getMetadata(formatMetadataKey, target, propertyKey); //問題出在這里
}


const person3 = new Greeter4('test');

console.log(person3.greet());

請具體解釋一下Reflect-metadata的具體作用和相關(guān)api,或者是否有中文資料及文檔

以上代碼運行報出錯誤

clipboard.png

沒有能夠取出元數(shù)據(jù)

回答
編輯回答
雨蝶

請把formatMetadataKey的聲明寫到代碼最上方,這里設(shè)置metadata的時候,formatMetadataKey的值還是undefined,自然后面就拿不到具體的metadata了

2017年10月14日 02:38