typescript - 装饰器的运行顺序是什么?

标签 typescript decorator

我不明白为什么结果是“directive before component”。

function Component(component) {
    console.log('selector: ' + component.selector);
    console.log('template: ' + component.template);
    console.log('component init');
    return (target: any) => {
        console.log('component call');
        return target;
    }
}

function Directive() {
    console.log('directive init');
    return (target: any) => {
        console.log('directive call');
        return target;
    }

}

@Component({selector: 'person',template: 'person.html'})
@Directive()
class Person {}

let p = new Person();

输出:

selector: person
template: person.html
component init
directive init
directive call
component call

组件调用不应该在指令调用之前吗?

最佳答案

装饰器表达式被自上而下调用,并产生装饰器。
装饰器自身以相反的方向运行,从下到上:

@a @b x
// bit like
{
  const decA = a
  const decB = b
  decA(decB(x))
}

在你的例子中

{
  const decComp = Component({selector: 'person', template: 'person.html'})
  // selector: person
  // template: person.html
  // component init
  const decDirective = Directive()
  // directive init
  decComp(decDirective(Person))
  // directive call
  // component call
}

Reference

关于typescript - 装饰器的运行顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758235/

相关文章:

python - 这个 python 装饰器是如何工作的?

python - 在 Python 中使用装饰器进行类型检查

javascript - 如何在javascript中根据ID连接匹配的字符串?

angular - 进入生产模式 Angular 4 时,类型 {} 上不存在属性 'address'

typescript - 如何从列表对象中获取选定项的索引

python - 为什么@decorator 不能装饰静态方法或类方法?

python - 装饰器来代替重复的面向对象代码?

decorator - vuex 不加载用 vuex-module-decorators 装饰的模块

linux - Typescript 在 Linux 上构建 Sublime Text 3 - [Errno 20] 不是目录

typescript - 为什么 Typescript 不允许使用整个精炼类型?