【发布时间】:2019-11-05 14:47:13
【问题描述】:
我有一个类 Car 包含汽车的一些信息,包括车牌,现在我想验证属性车牌,所以我以这种方式使用属性装饰器:
class Car{
@validate
public plate: string;
public model: string;
// extra info
constructor(plate: string, model: string){
this.plate= plate;
this.model = model;
}
toString(): string{
return `Car: ${this.plate} - ${this.model}`;
}
}
然后我有如下属性装饰器函数:
function validate(target: any, propertyKey: string){
let value = target[propertyKey];
Object.defineProperty(target, propertyKey, {
get: () => value,
set: (newValue) => {
const pattern = /^[A-Z]{2}\s?[0-9]{3}\s?[A-Z]{2}$/;
if(pattern.test(newValue)){
value = newValue;
} else {
console.error('Non valid plate: ', newValue);
//value = undefined;
}
}
})
}
现在,如果我以这种方式测试我的代码:
const car1 = new Car('IT123UE', 'Car1Model');
console.log('1 - ', car1.toString());
const car2 = new Car('IT000000UE', 'Car2Model');
console.log('2 - ', car2.toString());
我明白了:
1 - Car: IT123UE - Car1Model
Non valid plate: IT000000UE
2 - Car: IT123UE - Car2Model <-- why print car1.plate if car2.plate is not valid and this is car2 object?
我已经使用 value = undefined; 解决了在我的验证函数中的 else 中,但我不知道为什么在我的 car2.plate 中我得到 car1.plate 值。 另一个测试,如果我改变顺序:
const car2 = new Car('IT000000UE', 'Car2Model');
console.log('2 - ', car2.toString());
const car1 = new Car('IT123UE', 'Car1Model');
console.log('1 - ', car1.toString());
我明白了:
Non valid plate: IT000000UE
2 - Car: undefined - Car2Model <- now is undefinied
1 - Car: IT123UE - Car1Model
我的预期,但为什么之前没有工作?
我正在使用 TS 3.4.5 和 VS Code,并且在 tsconfig 中我有
"target": "es6",
"experimentalDecorators": true,
【问题讨论】:
标签: typescript decorator typescript-decorator