Decorator 装饰器
简介
装饰器(Decorator)是一种与类(class)相关的语法,用来修改类、类方法和类属性。装饰器是一种函数,写成@ + 函数名。它可以放在类、类方法和类属性的定义前面。
@frozen
class Foo {
@
configurable(false)
@
enumerable(true)
method() {}
@
throttle(500)
expensiveMethod() {}
}
类的装饰
装饰器可以用来装饰整个类。
@testable
class MyTestableClass {
}
function testable(target
) {
target
.isTestable
= true;
}
MyTestableClass
.isTestable
如果觉得一个参数不够用,可以在装饰器外面再封装一层函数。
function testable(isTestable
) {
return function(target
) {
target
.isTestable
= isTestable
;
}
}
@
testable(true)
class MyTestableClass {}
MyTestableClass
.isTestable
@
testable(false)
class MyClass {}
MyClass
.isTestable
方法的装饰
装饰器不仅可以装饰类,还可以装饰类的属性。
class Person {
@readonly
name() { return `${this.first} ${this.last}` }
}
function readonly(target
, name
, descriptor
){
descriptor
.writable
= false;
return descriptor
;
}
注:修饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,修饰器能在编译阶段运行代码。也就是说,修饰器本质就是编译时执行的函数。