如何正确定义装饰器?

时间:2019-07-14 09:47:46

标签: javascript

我找到了这个装饰器example

为什么会引发错误:Uncaught SyntaxError: Invalid or unexpected token

第三个参数“描述符”从何而来,为什么它有一个.value?

class Math {
  @log
  add(a, b) {
    return a + b;
  }
}

function log(target, name, descriptor) {
  var oldValue = descriptor.value;

  descriptor.value = function() {
    console.log(`Calling "${name}" with`, arguments);

    return oldValue.apply(null, arguments);
  };

  return descriptor;
}

const math = new Math();

// passed parameters should get logged now
math.add(2, 4);

2 个答案:

答案 0 :(得分:0)

我认为您需要将它们与编译器一起使用。

答案 1 :(得分:0)

装饰者当前是提案草案(请参见https://tc39.es/proposal-decorators/)。

此外,您当前的代码正在使用旧式语法。如果您转到babel并启用相关标志(stage-2和旧版装饰器语法),它将起作用。

请参见babel example并打开控制台

相关问题