随着 ES6 和 TypeScript 中类的引入,在某些场景须要在不改变原有类和类属性的基础上扩展些功能,这也是装饰器出现的缘由。javascript
做为一种能够动态增删功能模块的模式(好比 redux 的中间件机制),装饰器一样具备很强的动态灵活性,只需在类或类属性以前加上 @方法名
就完成了相应的类或类方法功能的变化。html
不过装饰器模式仍处于第 2 阶段提案中,使用它以前须要使用 babel 模块 transform-decorators-legacy
编译成 ES5 或 ES6。java
在 TypeScript 的 lib.es5.d.ts 中,定义了 4 种不一样装饰器的接口,其中装饰类以及装饰类方法的接口定义以下所示:react
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;
复制代码
下面对这两种状况进行解析。git
当装饰的对象是类时,咱们操做的就是这个类自己
。es6
@log
class MyClass { }
function log(target) { // 这个 target 在这里就是 MyClass 这个类
target.prototype.logger = () => `${target.name} 被调用`
}
const test = new MyClass()
test.logger() // MyClass 被调用
复制代码
因为装饰器是表达式,咱们也能够在装饰器后面再添加提个参数:github
@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 的写法以下:redux
@connect(mapStateToProps, mapDispatchToProps)
export default class MyComponent extends React.Component {}
复制代码
通过上述分析,咱们知道了上述写法等价于下面这种写法:babel
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 倒序后,装饰器方法会至里向外执行。