类的装饰器
@decoratorclass A{}function decorator(target) {target.dec = true;}
上述代码给类A添加了一个静态属性。装饰器的实质就是调用函数,让代码看起来更简单明了。类的装饰器函数接受一个参数,代表这个类。即上述代码中 target === A。如果想要传入多个参数,可以利用闭包。
类的装饰器基本上可以用下面代码来实现。
class A{}A = decorator(A) || A
方法的装饰器
class A{@readonlysay() {}}function readonly(p, key, descriptor) {// p 即 A.prototype// key 即 'say'// descriptor 即 say在A.prototype上的描述对象// 默认是// {// value: specifiedFunction,// enumerable: false,// configurable: true,// writable: true// };}
可以看出,方法的装饰器接受三个参数:类的原型对象、方法名、描述对象。
方法的装饰器可以用下面的代码来实现。
let descriptor = {value: function say() {},enumerable: false,configurable: true,writable: true};descriptor = readonly(A.prototype, 'say', descriptor) || descriptor;Object.defineProperty(A.prototype, 'say', descriptor);
目前,装饰器模式并没有被支持,所以暂时先这样。
