Angular 6属性装饰器问题

时间:2018-12-27 00:19:51

标签: javascript angular decorator

嘿,我正在尝试测试以下示例装饰代码。 它看起来很简单,但是当我运行它时,出现以下错误 “无法读取未定义的属性”名字”。 似乎“ 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 
    }); 
  } 
} 

1 个答案:

答案 0 :(得分:0)

您的代码唯一的问题是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 
    }); 
  } 
} 

在您的示例中,这是因为target界面中的参数PropertyDecorator是对应用装饰器的对象的引用。