If you need to get superclass methods as well, you can call Object.getPrototypeOf()
repeatedly until you find them all. You'll probably want to stop when you get to Object.prototype
, because the methods in there are fundamental and you usually don't want to touch them with any code that uses reflection.
The question Get functions (methods) of a class has an answer that includes a function for doing this, but it had a few shortcomings (including using a loop condition which had a side effect of modifying a function argument, which I figure makes two questionable code style choices in a single line of code...), so I've rewritten it here:
export function listMethodNames (object, downToClass = Object)
{
// based on code by Muhammad Umer, https://stackoverflow.com/a/31055217/441899
let props = [];
for (let obj = object; obj !== null && obj !== downToClass.prototype; obj = Object.getPrototypeOf(obj))
{
props = props.concat(Object.getOwnPropertyNames(obj));
}
return props.sort().filter((e, i, arr) => e != arr[i+1] && typeof object[e] == 'function');
}
As well as fixing the bug in the original code (which didn't copy the object into another variable for the loop, so by the time it was used for filtering in the return line it was no longer valid) this gives an optional argument to stop the iteration at a configurable class. It'll default to Object
(so Object
's methods are excluded; if you want to include them you can use a class that doesn't appear in the inheritance chain... perhaps making a marker class e.g. class IncludeObjectMethods{}
might make sense). I've also changed the do
loop to a clearer for
loop and rewritten the old-style function ...
filter function into an ES6 arrow function to make the code more compact.