装饰器本质上提供了对被装饰对象 的操作,在运行时被调用。
因为对于同一对象来说,可同时运用多个装饰器,然后装饰器中又可对被装饰对象进行任意的修改甚至是替换掉实现,直观感觉会有一些主观认知上的错觉,需要通过代码来验证一下。
比如,假若每个装饰器都对被装饰对象的有替换,其结果会怎样?
多个装饰器的应用通过编译运行以下示例代码并查看其结果可以得到一些直观感受:
function f() { console.log("f(): evaluated"); return function(_target: any, key: string, descriptor: PropertyDescriptor) { const original = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`[f]before ${key} called`, args); const result = original.apply(this, args); console.log(`[f]after ${key} called`); return result; }; console.log("f(): called"); return descriptor; }; } function g() { console.log("g(): evaluated"); return function(_target: any, key: string, descriptor: PropertyDescriptor) { const original = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`[g]before ${key} called`, args); const result = original.apply(this, args); console.log(`[g]after ${key} called`); return result; }; console.log("g(): called"); return descriptor; }; } class C { @f() @g() foo(count: number) { console.log(`foo called ${count}`); } } const c = new C(); c.foo(0); c.foo(1);