- 类修饰器、方法修饰器,不存在函数修饰器,会出现变量提升,同一个方法上有多个修饰器,会像剥洋葱一样,先从外到内进入,然后由内向外执行
class Person {
constructor() {}
@dec(1)
@dec(2)
name() {
console.log('霖呆呆')
}
}
function dec(id) {
console.log('out', id);
return function(target, key, descriptor) {
console.log(id);
}
}
var person = new Person()
person.name()
//结果
out 1
out 2
2
1
霖呆呆
外层修饰器dec(1)
先进入,但是内层修饰器dec(2)
先执行。
- 伪Decorator
@addSkill
class Person { }
function addSkill(target) {
target.say = "hello world";
}
console.log(Person['say']) //'hello world'
装饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,装饰器能在编译阶段运行代码。也就是说,装饰器本质就是编译时执行的函数。