ts 遍历Class上的属性和方法

interface Type<T> extends Function {
  new (...args: any[]): T;
}

class Data {
  name = "ajanuw";
  echo() {}
  get info() {
    return {};
  }
}

function cls<T>(value: Type<T>) {
  const ctx: any = new value();

  console.log(Object.keys(ctx)); // [ 'name' ]

  const prototype = Object.getPrototypeOf(ctx);
  console.log(Reflect.ownKeys(prototype)); // [ 'constructor', 'echo', 'info' ]
  // console.log(Object.getOwnPropertyDescriptors(prototype))

  // {
  //   value: [Function: echo],
  //   writable: true,
  //   enumerable: false,
  //   configurable: true
  // }
  console.log(Object.getOwnPropertyDescriptor(prototype, "echo"));

  // {
  //   get: [Function: get info],
  //   set: undefined,
  //   enumerable: false,
  //   configurable: true
  // }
  console.log(Object.getOwnPropertyDescriptor(prototype, "info"));
}

cls(Data);
posted @ 2020-12-08 10:27  Ajanuw  阅读(3419)  评论(0编辑  收藏  举报