我看到babel.js修饰器(在“阶段1”中可用)实现了https://github.com/wycats/javascript-decorators上的规范。看起来修饰器只限于(1)类,(2)访问器和(3)方法。在我的情况下,我想在普通的函数上使用装饰器,就像这样:
@chainable
function foo() { }
其中(仅为例子)
function chainable(fn) {
return function() {
fn.apply(this, arguments);
return this;
};
}
我不认为有任何逻辑上的理由说明为什么修饰器不能应用于函数。我的问题是,是否有某种方法可以实现这一点?或者,是否有某些很好的原因说明函数不能被装饰?
事实证明,在https://github.com/wycats/javascript-decorators/issues/4上提出了这个问题。
const func = someDecorator('abc')((x, y) => { return x + y });
,而非const func = @someDecorator('abc') (x, y) => { return x + y };
?在我看来,在这种情况下,那个微小的额外语法并没有给你带来任何好处。 - Ajedi32decorator1('abc')(decorator2('def')(decorator3('ghi')((x, y) => ...)))
和@decorator1('abc') @decorator2('def') @decorator3('ghi') (x, y) => ...
两种方式。实际上,将第一种写法输完花费的时间比应该花费的时间还要长,因为需要确保括号配对正确。 - Andy E