装饰器的使用

在 create-react-app 搭建的项目中使用装饰器

  1. 执行yarn eject命令,暴露出配置项

  2. 因为装饰器是新的提案,许多浏览器和 Node 环境并不支持,所以我们需要安装插件:@babel/plugin-proposal-decorators。使用create-react-app创建的项目自带这个插件,不过我们需要配置一下,找到package.json文件加入一下代码:

1
2
3
4
5
6
7
{
"babel": {
"presets": ["react-app"],

"plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]]
}
}

另外 vscode 可能会提示你需要配置tsconfigjsconfig文件,我们在项目根目录创建jsconfig.js,并写入:

1
2
3
4
5
{
"compilerOptions": {
"experimentalDecorators": true
}
}

这样就能愉快的在项目中使用装饰器了

装饰器的使用

使用装饰器修饰类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//声明一个装饰器
function fn(target) {
//这个函数的`target`指的就是装饰器要修饰的类
target.test = false;
}

@fn //使用装饰器
class Person {
//声明一个类
}
@fn
class Dog {
//声明另一个类
}

console.log(Person.test); //false
console.log(Dog.test); //false

输出结果

可以看到Person类和Dog类下面多出了一个test属性,这就体现了装饰器的优点,无需更改类的内部代码也无需去继承就可以给类添加新功能

使用装饰器传参

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@fn
@fn2(5)
class Person {}

function fn(target) {
target.test = false;
}

function fn2(value) {
return function (target) {
//这个函数的`target`指的就是装饰器要修饰的类
target.count = value;
};
}

console.log(Person.test);
console.log(Person.count);

声明一个装饰器fn2,它接收一个值,并且返回一个函数,这个函数的target指的就是装饰器要修饰的类
输出结果

使用装饰器添加实例属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@fn
@fn2(5)
@fn3
class Person {}

function fn(target) {
target.test = false;
}

function fn2(value) {
return function (target) {
target.count = value;
};
}

function fn3(target) {
target.prototype.foo = "hhh"; // target指的就是装饰的类,在类的原型对象上添加一个属性foo
}

const test1 = new Person(); // new一个实例出来
console.log(test1.foo);

输出结果

实现一个混入 mixins 功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 实现一个mixins功能
export function mixins(...list) {
return function (target) {
Object.assign(target.prototype, ...list);
};
}

import { mixins } from "./mixins";

const Test = {
test() {
console.log("这是测试");
},
};

@mixins(Test)
class Myclass {}

const newMyclass = new Myclass();
newMyclass.test(); //这是测试

使用装饰器修饰类的成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@fn
@fn2(5)
@fn3
class Person {
@readonly message = "hello";
}

function fn(target) {
target.test = false;
}

function fn2(value) {
return function (target) {
target.count = value;
};
}

function fn3(target) {
target.prototype.foo = "hhh";
}

function readonly(target, name, descriptor) {
console.log(target); //目标类的原型对象 xxx.prototype
console.log(name); // 被修饰的类的成员名称
console.log(descriptor);
/*被修饰的类的成员的描述对象:
configurable: 能否使用delete、能否需改属性特性、或能否修改访问器属性、,false为不可重新定义,默认值为true
enumerable: 是否被遍历,对象属性是否可通过for-in循环,flase为不可循环,默认值为true
initializer: 对象属性的默认值,默认值为undefined
writable: 对象属性是否可修改,flase为不可修改,默认值为true
*/

descriptor.writable = false;
}

const test1 = new Person();
test1.message = "你好";

它接收三个参数,具体看以上代码注释

输出结果


装饰器的使用
https://zouhualu.github.io/20211223/装饰器的使用/
作者
花鹿
发布于
2021年12月23日
许可协议