简体   繁体   中英

Is there a way to see all static variables and methods of a class in Typescript or ES6?

Similar to the Object.keys method which will return a list of all the key names attached to an object, is there a way to return all static variable names and all the static method names attached to a class?

Typescript Example:

class FindStatics {
  static num1:string = 'Num 1';
  static num2:string = 'Num 2';
  notStatic:string = "I'm not static";
  static concat ():string {
    return `${FindStatics.num1} loves ${FindStatics.num2}`
  }
  addToNonStatic(str:string):string {
    return `${this.notStatic} + ${str}`;
  }
}

What I would like to do is get the names of only the static variable and method names; so in the above example I would like num1 , num2 , and concat returned.

So as it turns out, you can just use the Object.keys method to get a list of all the static variable and method names attached to a class. ES6 classes are mostly just syntactical sugar to ES5. All static properties are inherited by the class, this also works for subclassing as well, we actually get a real prototype link between a subclass constructor function and the superclass constructor.

Therefore to return all static variable and method names for the example:

Object.keys(FindStatics);

@Kirkify, Object.keys doesn't return names of methods in my browser, because they're not enumerable.

方法名称不是从 Object.keys 返回的

For anyone who stumbles upon it, getOwnPropertyNames can be the solution.

Object.getOwnPropertyNames(FindStatics) === [
  "length", "prototype", "concat", "name", "num1", "num2"
]

const lengthPrototypeAndName = Object.getOwnPropertyNames(class {})
Object.getOwnPropertyNames(FindStatics).filter(
  k => !lengthPrototypeAndName.includes(k)
) === ["concat", "num1", "num2"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM