ES6 decorator 装饰器
装饰器由 “@” + 函数名 构成,作用是给类class或类属性添加额外功能。
类装饰器
@testable
class MyTestableClass {
// ...
}
function testable(target) {
target.isTestable = true;
target.prototype.isOtherable = true;
}
// 可执行如下
MyTestableClass.isTestable // true
上面代码中,@testable
就是一个装饰器。
它修改了MyTestableClass
这个类的行为,为它加上了静态属性isTestable和实例属性isOtherable
。
testable
函数的参数target
是MyTestableClass
类本身。
或闭包写法:
function testable(isTestable) {
return function(target) {
target.isTestable = isTestable;
}
}
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true
上面代码中,相当于传递闭包属性 isTestable 给装饰器函数使用。
属性装饰器
class Person {
@readonly
name() { return `${this.first} ${this.last}` }
}
function readonly(target, name, descriptor){
// descriptor对象原来的值如下
// {
// value: specifiedFunction,
// enumerable: false,
// configurable: true,
// writable: true
// };
descriptor.writable = false;
return descriptor;
}
readonly(Person.prototype, 'name', descriptor);
// 类似于
Object.defineProperty(Person.prototype, 'name', descriptor);
上面代码中,装饰器readonly
用来装饰“类”的name
方法。
vue-property-decorator @Watch
类似属性装饰器。
详见:https://es6.ruanyifeng.com/#docs/decorator