在类装饰器中访问此上下文

时间:2018-08-17 08:29:17

标签: javascript

我的装饰器

function vote(target) {
  target.vote = (val = '') => {
    console.log(target.name + val);
  }
}


class Cat {
  @vote
  name = 'britanik';
  meow() { return `${this.name} says Meow!`}
}
let garfield = new Cat();

garfield.vote('please .....');

但是target.name未定义为什么?

1 个答案:

答案 0 :(得分:2)

将目标设为正常功能,它应该可以正常工作。

   function vote(target) {
  target.vote = function(val=""){
    console.log(this.name + val);
  };
}

class Cat {
  @vote name = "britanik";
  meow() {
    return `${this.name} says Meow!`;
  }
}
let garfield = new Cat();
garfield.vote("please .....");