![](/img/trans.png)
[英]Angular 2 @Input() decorator for object with Date type property
[英]Angular 6 Property decorator issue
嘿,我正在嘗試測試以下示例裝飾代碼。 它看起來很簡單,但是當我運行它時,出現了以下錯誤“無法讀取未定義的屬性” firstname”。似乎“ this”不能引用當前上下文。
class Customer {
@hashify
public firstname: string;
public lastname: string;
constructor(firstname : string, lastname : string) {
this.firstname = firstname;
this.lastname = lastname;
}
}
function hashify(target: any, key: string) {
var _value = this[key];
var getter = function () {
return '#' + _value;
};
var setter = function (newValue) {
_value = newValue;
};
if (delete this[key]) {
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
您的代碼唯一的問題是, this
值不正確。 通過將該值更改為target
,您的代碼可以正常工作。
class Customer {
@hashify
public firstname: string;
public lastname: string;
constructor(firstname : string, lastname : string) {
this.firstname = firstname;
this.lastname = lastname;
}
}
function hashify(target: any, key: string) {
var _value = target[key];
var getter = function () {
return '#' + _value;
};
var setter = function (newValue) {
_value = newValue;
};
if (delete target[key]) {
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
在您的示例中,這是因為PropertyDecorator
接口中的參數target
是對應用裝飾器的對象的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.