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)
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With