Math
has static method where you can call directly like Math.abs()
while Date
has static method like Date.now()
and also instance method where you need to create new instance first var time = new Date()
to call time.getHours()
.
// The instance method of Date can be found on `Date.prototype` so you can just call:
var keys = Object.getOwnPropertyNames(Date.prototype);
// And for the static method
var keys = Object.getOwnPropertyNames(Date);
// But if the instance already created you need to
// pass its constructor
var time = new Date();
var staticKeys = Object.getOwnPropertyNames(time.constructor);
var instanceKeys = Object.getOwnPropertyNames(time.constructor.prototype);
Of course you will need to filter the obtained keys for the static method to get actual method names, because you can also get length, name
that aren't a function on the list.
But how if we want to obtain all available method from class that extend another class?
Of course you will need to scan through the root of prototype like using __proto__
. For saving your time you can use script below to get static method and deep method instance.
// var keys = new Set();_x000D_
function getStaticMethods(keys, clas){_x000D_
var keys2 = Object.getOwnPropertyNames(clas);_x000D_
_x000D_
for(var i = 0; i < keys2.length; i++){_x000D_
if(clas[keys2[i]].constructor === Function)_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
}_x000D_
_x000D_
function getPrototypeMethods(keys, clas){_x000D_
if(clas.prototype === void 0)_x000D_
return;_x000D_
_x000D_
var keys2 = Object.getOwnPropertyNames(clas.prototype);_x000D_
for (var i = keys2.length - 1; i >= 0; i--) {_x000D_
if(keys2[i] !== 'constructor')_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
_x000D_
var deep = Object.getPrototypeOf(clas);_x000D_
if(deep.prototype !== void 0)_x000D_
getPrototypeMethods(keys, deep);_x000D_
}_x000D_
_x000D_
// ====== Usage example ======_x000D_
// To avoid duplicate on deeper prototype we use `Set`_x000D_
var keys = new Set();_x000D_
getStaticMethods(keys, Date);_x000D_
getPrototypeMethods(keys, Date);_x000D_
_x000D_
console.log(Array.from(keys));
_x000D_
If you want to obtain methods from created instance, don't forget to pass the constructor
of it.