2016-01-13 55 views
12

How to implement a typescript decorator?是關於如何在打字稿中使用裝飾器的一個很好的例子。如何將實例變量傳入打印機裝飾參數?

考慮下面的情況下,

class MyClass { 
    @enumerable(false) 
    get prop() { 
     return true; 
    } 

    @property({required: true}) //here pass constant is no issue 
    public startDateString:string; 

    @property({afterDate: this.startDateString}) //how to pass startDateString here? 
    public endDateString:string; 
} 

function enumerable(isEnumerable: boolean) { 
    return (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => { 
     descriptor.enumerable = isEnumerable; 
     return descriptor; 
    }; 
} 

我什麼都試過,但似乎我沒有辦法通過startDateString到裝飾的說法。 startDateString可能是一個變量,一個函數和一個參考。

+0

這可能是可能的,具體取決於_how_和_when_您需要使用傳入的值。我知道你需要將'startDateString'的errrr ... _instance value_傳遞給應用到'endDateString'的裝飾器,但是你打算在裝飾器中使用它做什麼?根據具體情況,可以通過裝飾器獲取實例成員。 –

回答

6

你想要做的是不可能的。

當類聲明時,裝飾器被調用,並且此時沒有實例傳入裝飾器。

例如,對於這樣的代碼:

class MyClass { 
    startDateString: string; 
    @property({ afterDate: this.startDateString }) 
    endDateString: string; 
} 
let myClass = new MyClass(); 
  1. MyClass被聲明。
  2. 裝修工在MyClass上運行。在這一點上沒有實例存在,並且裝飾器參數中的this引用全局對象 - 而不是實例。
  3. new MyClass()被調用並且實例被創建。這一步不會調用裝飾器。那已經發生了。

看看在編譯的JavaScript以供參考:

var MyClass = (function() { 
    // -- 1 -- 
    function MyClass() { 
    } 
    // -- 2 -- 
    __decorate([ 
     // see here... `this` is equal to the global object 
     property({ afterDate: this.startDateString }) 
    ], MyClass.prototype, "endDateString", void 0); 
    return MyClass; 
})(); 
// -- 3 -- 
var myClass = new MyClass(); 

注意,使用this.startDateString因爲this的類型爲any不扔在這裏編譯錯誤。

那麼通過傳遞一個實例屬性試圖在這裏做什麼沒有意義,也是不可能的。

你可以做的是讓startDateString靜態然後像這樣傳遞它:@property({ afterDate: MyClass.startDateString })

+0

謝謝。但在我的情況下,它不能是靜態的類變量。它必須是一個實例變量。 – new2cpp

+0

@ new2cpp你可以做的一件事是傳入一個字符串或函數,它傳遞一個類的實例並返回屬性值。類似於'{afterDate:「startDateString」}或'{afterDate:(instance:MyClass)=> instance.startDate}'。然後,您可以稍後使用此信息來獲取該屬性的值。這是一個很冒險的解決方案,它是一種很好的混淆查看代碼的人的方法。 –

3

您無法從屬性定義訪問對象屬性。

在定義屬性時調用裝飾器。

訪問屬性時,可以使用getter或setter來獲取控件。

相關問題