ES6 Decorator 装饰器

mac2025-10-28  17

Decorator 装饰器

简介 装饰器(Decorator)是一种与类(class)相关的语法,用来修改类、类方法和类属性。装饰器是一种函数,写成@ + 函数名。它可以放在类、类方法和类属性的定义前面。 @frozen class Foo { @configurable(false) @enumerable(true) method() {} @throttle(500) expensiveMethod() {} } 类的装饰 装饰器可以用来装饰整个类。 @testable class MyTestableClass { // ... } // target是MyTestableClass类本身。 function testable(target) { target.isTestable = true; } MyTestableClass.isTestable // true 如果觉得一个参数不够用,可以在装饰器外面再封装一层函数。 function testable(isTestable) { return function(target) { target.isTestable = isTestable; } } @testable(true) class MyTestableClass {} MyTestableClass.isTestable // true @testable(false) class MyClass {} MyClass.isTestable // false 方法的装饰 装饰器不仅可以装饰类,还可以装饰类的属性。 class Person { @readonly name() { return `${this.first} ${this.last}` } } // target是Person.prototype function readonly(target, name, descriptor){ // descriptor对象原来的值如下 // { // value: 属性值, // enumerable: false, // 是否可遍历 // configurable: true, // 是否可配置,即是否可用delete 删除属性或使用Object.defineProperty设置属性 // writable: true // 是否可写 // }; descriptor.writable = false; return descriptor; }

注:修饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,修饰器能在编译阶段运行代码。也就是说,修饰器本质就是编译时执行的函数。

最新回复(0)