装饰器
原创大约 1 分钟
装饰器(Decorator)
其实是一种特殊的函数,这个函数仅在代码加载阶段执行一次,可以被应用于类、属性、方法和参数上,从而改变原有的功能。
TypeScript或ArkTS的装饰器
,其实就对应于Java中的注解(Annotation)
。
和注解
一样,装饰器
也使用@
语法。
// 普通装饰器
function test() {
console.log("this is a function");
// 返回一个回调函数,成为装饰器工厂
return () => {console.log("test")};
}
// 如果没有装饰器工厂,那么调用时写成@test就可以了
// 所以这里会先执行@test,然后再执行回调函数部分@test()
@test()
class A {}
装饰器
可以组合叠加组合。
组合的装饰器首先会从上至下
依次执行所有的装饰器工厂。
拿到真正的装饰器后,然后再从下至上
地依次执行所有的装饰器。
function f1() {
console.log("f1");
}
function f2() {
console.log("f2");
}
function f3() {
console.log("f3 out");
return () => {console.log("f3 in")};
}
function f4() {
console.log("f4 out");
return () => {console.log("f4 in")};
}
/* 输出顺序和装饰器的在代码中的出现次序有关,在这里的顺序是
* f3 out
* f4 out
* f4 in
* f3 in
* f2
* f1
*/
@f1
@f2
@f3()
@f4()
class A {}
按照装饰的对象,装饰器可以分为类装饰器
、属性装饰器
、方法装饰器
、参数装饰器
和访问器装饰器
。
// 类装饰器
@classDecorator
class Person {
// 属性装饰器
@propertyDecorator
name: string = "";
// 方法装饰器
@methodDecorator
show(
// 参数装饰器
@parameterDecorator
num: number
) {}
// 访问器装饰器
@accessorDecorator
get speed() {}
}
感谢支持
更多内容,请移步《超级个体》。