2017-01-17 3 views
1

クラスアクセサーデコレータでインスタンス化されたクラスコンテキストをバインドする方法を理解できません。一言で言えば私のクラスには、次のとおりです。アクセサーデコレータとインスタンス化されたクラスコンテキスト

class A { 
    protected persistProperty(a, b) { 
     // ... 
    } 
} 

class C extends A { 
    @validatorTest 
    public set coolStuff(email: string) { 
     this.persistProperty('company.email', email); 
    } 
} 

デコレータ:

let foo = new C(); 

c.coolStuff = '[email protected]'; 

私は次のエラーを取得する:

function validatorTest(
    target: any, 
    propertyKey: string, 
    descriptor: TypedPropertyDescriptor<string> 
) { 
    const oldSet = descriptor.set; 

    descriptor.set = (value: string) => { 
     if (value && !value.match(...)) { 
      throw new Error(); 
     } 

     oldSet(value); 
    } 
} 

今の問題は、私はアクセサを使用する場合に発生します

TypeError: Cannot read property 'persistProperty' of undefined 

これまで説明したように、インスタンス化されたクラスのコンテキストはデコレータにバインドされていません。私はここで間違って何をしていますか?

答えて

1

を試してみてください。だから、意図したとおり、この作品(もマダラの答えのおかげで):ソリューションの

function validatorTest(
    target: any, 
    propertyKey: string, 
    descriptor: TypedPropertyDescriptor<string> 
) { 
    const oldSet = descriptor.set; 

    descriptor.set = function(value: string) { 
     if (value && !value.match(...)) { 
      throw new Error(); 
     } 

     oldSet.call(this, value); 
    } 
} 
2

これはTypeScriptの問題ではなく、thisを付けずにoldSet()を呼び出してthisのコンテキストを失ったことになります。

推測:どうやら、あなたは記述子のオーバーライドに矢印構文を使用することはできません..すべての後に、問題を自分自身を発見し、まあoldSet.call(this, value)

+0

パートは、自分の質問に答えた:) – nhaa123

+0

は、ありがとう、ありがとう、ありがとう。 – JonathanPeel

+0

@madaraは、この例では_forward_パラメータを簡単に使用できます。 JonathanPeel

関連する問題