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
1592

被折叠的 条评论
为什么被折叠?



