JavaScript - Decorator修饰器 - 让代码更干净

前言

最近做的项目中使用到了 状态管理 - Mobx,Mobx中就用到了ES7中所谓的修饰器,参考文档一番,将使用心得分享于大家。

一边挠头一边啃英文文档... 最近跟Mapbox杠上了... 难受...

修饰器简介

作为一种可以动态增删功能模块的模式(比如 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;

在下面修饰器的使用中我会将这两种情况进行解析。

修饰器的使用

1、作用于类的修饰器

当装饰的对象是类时,我们操作的就是这个类本身

@log
class 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)
2、作用于类方法的装饰器

与装饰类不同,对类方法的装饰本质是操作其描述符。可以把此时的装饰器理解成是 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 倒序后,装饰器方法会至里向外执行。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容