装饰器
  # 场景
- 数据上报
 - 请求公共参数
 - localstorage设置过期时间
 - 路由守卫
 
# 函数装饰器
用一个函数包装另一个函数,来扩展功能而不改变原始函数
function readonly(target, name, descriptor) {
  descriptor.writable = false;
  return descriptor;
}
class Point {
  constructor(x, y) {
    this._x = x;
    this._y = y;
  }
  @readonly
  get x() {
    return this._x;
  }
  set x(value) {
    this._x = value;
  }
}
const p = new Point(1, 2);
console.log(p.x); // 1
p.x = 3;
console.log(p.x); // 1
 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
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
在上面的例子中,我们定义了一个名为 readonly 的装饰器函数,它将方法的 writable 属性设置为 false。然后,我们使用 @readonly 装饰了 Point 类的 x 方法。这样,我们就可以通过访问 p.x 来读取 x 的值,但是不能通过调用 p.x = 3 来修改它的值。
上次更新: 2024/07/21, 21:46:04