装饰器(Decorator)是一种与类(class)相关
的语法,用来注释或修改类和类方法。 装饰器是一种函数,写成@ + 函数名
。它能够放在类和类方法的定义前面。 其实只是一个语法糖. 尚未正式发布, 还须要插件babel-plugin-transform-decorators-legacy
使用react
@testable
class MyTestableClass {
// ...
}
function testable(target) {
target.isTestable = true;
}
MyTestableClass.isTestable // true
复制代码
上面代码中,@testable
就是一个装饰器。它修改了MyTestableClass
这个类的行为,为它加上了静态属性isTestable
。testable
函数的参数target
是MyTestableClass
类自己。es6
也就是说,装饰器是一个对类进行处理的函数。装饰器函数的第一个参数,就是所要装饰的目标类。bash
function testable(target) {
// ...
}
复制代码
若是想传参,能够在装饰器外面再封装一层函数。babel
function testable(isTestable) {
return function(target) {
target.isTestable = isTestable;
}
}
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true
@testable(false)
class MyClass {}
MyClass.isTestable // false
复制代码
上面代码中,装饰器testable
能够接受参数,这就等于能够修改装饰器的行为。函数
注意,装饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,装饰器能在编译阶段运行代码。也就是说,装饰器本质就是编译时执行的函数。ui
前面的例子是为类添加一个静态属性,若是想添加实例属性,能够经过目标类的prototype
对象操做。lua
function testable(target) {
target.prototype.isTestable = true;
}
@testable
class MyTestableClass {}
let obj = new MyTestableClass();
obj.isTestable // true
复制代码
上面代码中,装饰器函数testable
是在目标类的prototype
对象上添加属性,所以就能够在实例上调用。spa
function testable(target) {
target.prototype.isTestable = true;
}
@testable
class MyTestableClass {}
let obj = new MyTestableClass();
obj.isTestable // true
复制代码
经常须要写成下面这样prototype
class MyReactComponent extends React.Component {}
export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);
复制代码
有了装饰器,就能够改写上面的代码。插件
@connect(mapStateToProps, mapDispatchToProps)
export default class MyReactComponent extends React.Component {}
复制代码
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);
复制代码
装饰器第一个参数是类的原型对象,上例是Person.prototype
,装饰器的本意是要“装饰”类的实例,可是这个时候实例还没生成,因此只能去装饰原型(这不一样于类的装饰,那种状况时target
参数指的是类自己);第二个参数是所要装饰的属性名,第三个参数是该属性的描述对象。
其他使用方法与类的装饰器相同(参数变为3个了~)
若是同一个方法有多个装饰器,会像剥洋葱同样,先从外到内进入,而后由内向外执行。
function dec(id){
console.log('evaluated', id);
return (target, property, descriptor) => console.log('executed', id);
}
class Example {
@dec(1)
@dec(2)
method(){}
}
// evaluated 1
// evaluated 2
// executed 2
// executed 1
复制代码
装饰器只能用于类和类的方法,不能用于函数,由于存在函数提高。
import React from 'react';
export default Component => class extends React.Component {
render() {
return <div style={{cursor: 'pointer', display: 'inline-block'}}>
<Component/>
</div>
}
}
复制代码
这个装饰器(高阶组件)接受一个 React 组件做为参数,而后返回一个新的 React 组件。实现很简单,就是包裹了一层 div,添加了一个 style,就这么简单。之后全部被它装饰的组件都会具备这个特征。 除了style还能够传参数
import React from 'react';
export default Component => class extends React.Component {
render() {
return <div test={'qwe'}>
<Component/>
</div>
}
}
复制代码
之后全部被它装饰的组件均可以从props
里面获取到test
. 他的值是'qwe'
。
发挥你的想象, 你能够写无数个很方便的高阶组件, 经过装饰器的方式, 让你的代码更简洁, 更帅
索引