Dismiss
  • Toggle Theme
  • View as Mobile

Deep log available methods on JavaScript Objects & Classes

Sometimes console.log won't give us all the available methods on a javascript Object or Class. This makes exploring the API of a given thing difficult.

To fix this we can use the utility function getMethods, below in this post, to deep log an object/class with all its methods.

I use this utility a lot when exploring new library APIs. Enjoy.

Example with console.log

Here's what console.log gives us when trying to inspect a class. It's empty 🥲.

Example with getMethods util

And here is what the helper function gives us. It lists the methods! Hooray 🎉

The code

This snippet is handy for debugging what is available on a given object or class.

/**
 * Retrieves methods from an object or class.
 * @param {Object} obj - The object to search.
 * @returns {Array} - An array of methods.
 */
function getMethods(obj) {
  return distinctDeepFunctions(obj).filter(name => name !== "constructor" && !~name.indexOf("__"))
}
/**
 * Checks if the property is a getter.
 * @param {Object} x - The object.
 * @param {string} name - The name of the property.
 * @returns {boolean} - True if it's a getter, otherwise false.
 */
function isGetter(x, name) {
  return (Object.getOwnPropertyDescriptor(x, name) || {}).get
}
/**
 * Checks if the property is a function.
 * @param {Object} x - The object.
 * @param {string} name - The name of the property.
 * @returns {boolean} - True if it's a function, otherwise false.
 */
function isFunction(x, name) {
  return typeof x[name] === "function"
}
/**
 * Retrieves all deep functions from an object.
 * @param {Object} x - The object to search.
 * @returns {Array} - An array of deep functions.
 */
function deepFunctions(x) {
  return x && x !== Object.prototype &&
    Object.getOwnPropertyNames(x)
    .filter(name => isGetter(x, name) || isFunction(x, name))
    .concat(deepFunctions(Object.getPrototypeOf(x)) || [])
}
/**
 * Retrieves distinct deep functions from an object.
 * @param {Object} x - The object to search.
 * @returns {Array} - An array of distinct deep functions.
 */
function distinctDeepFunctions(x) {
  return Array.from(new Set(deepFunctions(x)))
}

Originally from https://stackoverflow.com/questions/2257993/how-to-display-all-methods-of-an-object#answer-67975040

Here is the minified version

const isGetter = (x, name) => (Object.getOwnPropertyDescriptor(x, name) || {}).get
const isFunction = (x, name) => typeof x[name] === "function"
const deepFunctions = x => x && x !== Object.prototype && Object.getOwnPropertyNames(x)
  .filter(name => isGetter(x, name) || isFunction(x, name))
  .concat(deepFunctions(Object.getPrototypeOf(x)) || [])
const distinctDeepFunctions = x => Array.from(new Set(deepFunctions(x)))
const getMethods = (obj) => distinctDeepFunctions(obj).filter(name => name !== "constructor" && !~name.indexOf("__"))

Hope it helps. Props to Ciro Santilli for the original script.