js装饰器原理

装饰器原理

装饰器分为两类: 作用于类的装饰器,作用于方法的装饰器

1、原理

查看装饰器语法在babel-loader转换后的js代码,发现 调用装饰器函数 是对类class进行了一层封装,并返回新的class。

对应类或者方法可以有多个装饰器修饰

class Person {
   @readonly
   @valiable
   name() {
       return `${this.firstname}+${this.lastname}`;
   }
}

2、作用于 class 装饰器写法举栗

function log (target) {  // 默认传参为 被修饰的类
target.prototype.logger = () => {console.log('装饰器--被调用')};

}
@log // log 必须是函数 class Myclass {};

const test = new Myclass();
test.logger(); // 装饰器--被调用

// 在mobx中装饰器的应用最为广泛,@observable @action @computed @asyncAction

3、作用于 方法 饰器写法举栗

  // 对于类方法的修饰,实际上是操作其描述符

Object.defineProperty(obj, prop, descriptor);
class C {
@readonly (true);
method () {
console.log('cat--');
}
}

function readonly (value) {
// target: 类原型
// key: 被修饰的属性或者方法
// descriptor: 被修饰的属性或方法的描述符对象
return function (target, key, descriptor) {
descriptor.writable = !value;
return descriptor;
}
}

const c = new C();
c.method = () => {console.log('dog--');} // 重写了method这个类方法
c.method() // cat--
// 设置属性只读成功


原文地址:https://www.cnblogs.com/the-last/p/11230471.html