装饰器
场景
- 数据上报
- 请求公共参数
- 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); // 1p.x = 3;console.log(p.x); // 1在上面的例子中,我们定义了一个名为 readonly 的装饰器函数,它将方法的 writable 属性设置为 false。然后,我们使用 @readonly 装饰了 Point 类的 x 方法。这样,我们就可以通过访问 p.x 来读取 x 的值,但是不能通过调用 p.x = 3 来修改它的值。