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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM