Зачем нам нужен параметр «дескриптор» для декоратора метода? - PullRequest
0 голосов
/ 22 февраля 2020

Вот подпись метода-декоратора в машинописи:

declare type MethodDecorator = <T>(
  target: Object,
  propertyKey: string | symbol,
  descriptor: TypedPropertyDescriptor<T> // descriptor of the method passed as an argument
) => TypedPropertyDescriptor<T> | void;

Как вы можете видеть, третий параметр - PropertyDescriptor . Но я не понимаю, зачем нам эта информация в качестве аргумента функции. Мы можем получить дескриптор уже по Object.getOwnPropertyDescriptor(target, propertyKey).

Вот небольшой эксперимент, если вам интересно:

function testMethodDecorator(
    target: any,
    propertyKey: string,
    descriptor: PropertyDescriptor
  ) {
    const desc1 = Object.getOwnPropertyDescriptor(target, propertyKey);
    const desc2 = descriptor;

    console.log("Descriptor1 ==>", desc1);
    /* prints:
     Descriptor1 ==> { value: [Function],
                        writable: true,
                        enumerable: true,
                        configurable: true } */
    console.log("Descriptor1 ==>", desc2);
    /* prints:
     Descriptor1 ==> { value: [Function],
                        writable: true,
                        enumerable: true,
                        configurable: true } */

    console.log(desc1!.value === desc2!.value); // prints `true`
  }

  class A {
    @testMethodDecorator
    test() {
      console.log("hello, world");
    }
  }

Я что-то упустил или это действительно избыточный параметр?

...