Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the static methods of a class [duplicate]

Supposing we have a class like this:

class Foo {
   static bar () {}
}

We can call the bar static method using Foo.bar(). But how can we get an array containing only the static methods of the class?

From what I see, Object.getOwnPropertyNames(Foo) returns more than just the "bar" element.

How can we get only the static methods or filter out the non-static methods from Object.getOwnPropertyNames(Foo)?

like image 897
Ionică Bizău Avatar asked Feb 23 '16 15:02

Ionică Bizău


1 Answers

Object.getOwnPropertyNames(Foo) will not return instance methods. It will return other properties on the class Function though (length, name, prototype, etc) so you can write a function to filter these out:

class Foo{
    static one() {}
    two() {}
    three() {}
    static four() {}
}
const all = Object.getOwnPropertyNames(Foo)
    .filter(prop => typeof Foo[prop] === "function");
console.log(all); // ["one", "four"]

Note: This doesn't display any inherited static methods. It gets a little more messy as you'd need to do that on each function up the chain.

like image 117
CodingIntrigue Avatar answered Oct 04 '22 20:10

CodingIntrigue