什么是装饰器(Decorator)
装饰器(Decorator)是一种与类(class)相关
的语法,用来注释或修改类和类方法。
装饰器是一种函数,写成@ + 函数名
。它可以放在类和类方法的定义前面。
其实只是一个语法糖. 还没有正式发布, 还需要插件babel-plugin-transform-decorators-legacy
使用
装饰器(Decorator)使用
类的装饰器
@testable
class MyTestableClass {
// ...
}
function testable(target) {
target.isTestable = true;
}
MyTestableClass.isTestable // true
上面代码中,@testable
就是一个装饰器。它修改了MyTestableClass
这个类的行为,为它加上了静态属性isTestable
。testable
函数的参数target
是MyTestableClass
类本身。
也就是说,装饰器是一个对类进行处理的函数。装饰器函数的第一个参数,就是所要装饰的目标类。
function testable(target) {
// ...
}
如果想传参,可以在装饰器外面再封装一层函数。
function testable(isTestable) {
retur