随着 ES6 和 TypeScript 中类的引入,在某些场景需要在不改变原有类和类属性的基础上扩展些功能,这也是装饰器出现的原因。
装饰器简介
作为一种可以动态增删功能模块的模式(比如 redux 的中间件机制),装饰器同样具有很强的动态灵活性,只需在类或类属性之前加上 @方法名
就完成了相应的类或类方法功能的变化。
不过装饰器模式仍处于第 2 阶段提案中,使用它之前需要使用 babel 模块 transform-decorators-legacy
编译成 ES5 或 ES6。
在 TypeScript 的 lib.es5.d.ts 中,定义了 4 种不同装饰器的接口,其中装饰类以及装饰类方法的接口定义如下所示:
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
下面对这两种情况进行解析。
作用于类的装饰器
当装饰的对象是类时,我们操作的就是这个类本身
。
@logclass MyClass { }function log(target) { // 这个 target 在这里就是 MyClass 这个类 ??target.prototype.logger = () => `${target.name} 被调用`}const test = new MyClass()test.logger() // MyClass 被调用
由于装饰器是表达式,我们也可以在装饰器后面再添加提个参数:
@log('hi')class MyClass { }function log(text) { ?return function(target) { ???target.prototype.logger = () => `${text},${target.name} 被调用` ?}}const test = new MyClass()test.logger() // hello,MyClass 被调用
在使用 redux 中,我们最常使用 react-redux 的写法如下:
@connect(mapStateToProps, mapDispatchToProps)export default class MyComponent extends React.Component {}
经过上述分析,我们知道了上述写法等价于下面这种写法:
class MyComponent extends React.Component {}export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
作用于类方法的装饰器
与装饰类不同,对类方法的装饰本质是操作其描述符。可以把此时的装饰器理解成是 Object.defineProperty(obj, prop, descriptor)
的语法糖,看如下代码:
class C { ?@readonly(false) ?method() { console.log('cat') }}function readonly(value) { ?return function (target, key, descriptor) { // 此处 target 为 C.prototype; key 为 method; ???// 原 descriptor 为:{ value: f, enumarable: false, writable: true, configurable: true } ???descriptor.writable = value ???return descriptor ?}}const c = new C()c.method = () => console.log('dog')c.method() // cat
可以看到装饰器函数接收的三个参数与 Object.defineProperty 是完全一样的,具体实现可以看 babel 转化后的代码,主要实现如下所示:
var C = (function() { ?class C { ???method() { console.log('cat') } ?} ?var temp ?temp = readonly(false)(C.prototype, 'method', ???temp = Object.getOwnPropertyDescriptor(C.prototype, 'method')) || temp // 通过 Object.getOwnPropertyDescriptor 获取到描述符传入到装饰器函数中 ?if (temp) Object.defineProperty(C.prototype, 'method', temp) ?return C})()
再将再来看看如果有多个装饰器作用于同一个方法上呢?
class C { ?@readonly(false) ?@log ?method() { }}
经 babel 转化后的代码如下:
desc = [readonly(false), log] ???.slice() ???.reverse() ???.reduce(function(desc, decorator) { ?????return decorator(target, property, desc) || desc; ???}, desc);
可以清晰地看出,经过 reverse 倒序后,装饰器方法会至里向外执行。
相关链接
javascript-decorators
Javascript 中的装饰器
JS 装饰器(Decorator)场景实战
修饰器
Babel