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

Hao*_*Hao 12 decorator typescript

我不明白为什么结果是“组件之前的指令”。

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();
Run Code Online (Sandbox Code Playgroud)

输出:

selector: person
template: person.html
component init
directive init
directive call
component call
Run Code Online (Sandbox Code Playgroud)

不应该component call是之前吗directive call

HTN*_*TNW 15

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

@a @b x
// bit like
{
  const decA = a
  const decB = b
  decA(decB(x))
}
Run Code Online (Sandbox Code Playgroud)

在你的例子中

{
  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
}
Run Code Online (Sandbox Code Playgroud)

参考


bas*_*rat 8

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

不会。内部将在外部之前被调用。本质上

@C
@D
class Person {}
Run Code Online (Sandbox Code Playgroud)

变成类似于

C(D(class Person()))
Run Code Online (Sandbox Code Playgroud)