Контекст этого в аргументе декоратора машинописи, который является функцией стрелки - PullRequest
0 голосов
/ 29 сентября 2019

У меня есть декоратор метода машинописного текста, у которого есть аргумент типа функции. Я определяю эту функцию как функцию стрелки, но теряю контекст this. Мне нужна помощь в понимании того, почему первый фрагмент ниже не работает. Вот пример кода. Ссылка на stackblitz

function gamora(a: () => string) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {

    const originalMethod = descriptor.value;
    descriptor.value = function (...args) {
      this.name = a();
      return originalMethod.apply(this, args);
    }
    return descriptor;
  }
}

class MyClass {
  name = 'default';
  gamora = 'Gamora';

  @gamora(() => !!this && !!this.gamora ? this.gamora : 'nada')
  test1() {
    return `${this.name}!`;
  }
}

const my = new MyClass();
const test1Val = my.test1();
console.log('First', test1Val); // it prints nada

Так как мне нужно получить доступ к свойствам класса из этой функции аргумента декоратора, мне нужно перейти к приведенному ниже решению.

function carol(a: () => string) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {

    const originalMethod = descriptor.value;
    descriptor.value = function (...args) {
      this.name = a.call(this);
      return originalMethod.apply(this, args);
    }
    return descriptor;
  }
}

class MyClass {
  name = 'default';
  carol = 'Carol Danvers';

  @carol(function(){return this.carol})
  test2() {
    return `${this.name}!`;
  }
}

const my = new MyClass();
const test2Val = my.test2();
console.log('Second', test2Val); // this prints Carol Danvers
...