2016-01-13 50 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来获取控件。

相关问题