装饰器
装饰者模式:能够在不改变对象自身基础上,在程序运行期间给对象添加职责
装饰器只能针对类和类的属性,不能直接作用于函数(由于存在函数提升)
本质上是语法糖,借助 Object.defineProperty(target,name,descriptor)
添加和修改对象的属性
属性描述符
- 数据描述符
- 存取描述符
使用场景
- log
- time 统计方法执行的时间
- readonly/...
- debounce 对执行的方法执行防抖处理
- mobx 实践
类装饰器
log
js
function log(Class) {
return (...args) => {
console.log(args);
return new Class(...args);
};
}
@log
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const cat = new Animal("Hello kitty", 2);
// ["Hello kitty", 2]
console.log(cat.name);
// Hello kitty
属性装饰器
js
function log(target, name, descriptor) {
const original = descriptor.value;
if (typeof original === "function") {
descriptor.value = function (...args) {
console.log(`log for args: ${args}`);
try {
return original.apply(this, args);
} catch (e) {
console.log(`Error: ${e}`);
throw e;
}
};
}
return descriptor;
}
class Animal {
constructor(name) {
this.name = name;
}
@log
sayHello(name) {
console.log(`Hello ${name}, I'm ${this.name}`);
}
}
const cat = new Animal("Hello kitty");
cat.sayHello("Jack");
// log for args: Jack
// Hello Jack, I'm Hello kitty
参考