Exploring the world of JavaScript by dynamically retrieving all class functions

Is there a way to retrieve an array of all functions from a given class, including functions inherited from parent classes?

For instance:

class Foo extends Bar {
      funcA() {}
}

class Bar {
      funcB() {}
}

const instanceFoo = new Foo();

getClassFunctions(instanceFoo); // should return an array ['funcA', 'funcB'];

I've created a function that fetches the names of a class's functions, but it only works for properties belonging directly to the class.

const getAllFuncs = (obj) => {
    const proto = Object.getPrototypeOf(obj);
    const names = Object.getOwnPropertyNames(proto);
    return names.filter(name => typeof obj[name] === 'function' && name !== 'constructor');
}

Answer №1

To retrieve all functions from an object, you can loop through its prototypes, beginning with the object itself and not its prototype. The loop can stop when it reaches Object.prototype. During construction, methods may be added, hence starting with the object is important:

const getAllFuncs = (obj) => {
    // Keep track of checked names
    const checked = new Set();
    // Store function names to return
    const funcs = [];
    while (obj && obj !== Object.prototype) {
        for (const name of Object.getOwnPropertyNames(obj)) {
            if (name !== "constructor" && !checked.has(name)) {
                // Mark as checked
                checked.add(name);
                const value = obj[name];
                if (typeof value === "function") {
                    // Add to list of functions
                    funcs.push(name);
                }
            }
        }
        // Move up a level
        obj = Object.getPrototypeOf(obj);
    }
    return funcs;
};

The distinction between checked and funcs is necessary because an object might have a property named foo containing a non-function type, while its prototype could have a foo with a function. Although uncommon, this scenario is possible:

class Base {
    foo() {
    }
}
class Sub extends Base {
    constructor() {
        super();
        this.foo = 42;
    }
}

const sub = new Sub();
const names = getAllFuncs(sub);

In this case, names would exclude foo since sub.foo is assigned with 42, not a function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatically numbering table columns with custom language localization in JavaScript using Jquery

Is there a method to automatically number table data in a local or custom language? As a Bengali individual, I have figured out how to automatically number the first data of each row using css and js. However, I am uncertain about how to implement custom n ...

Having trouble getting card animations to slide down using React Spring

I am currently learning React and attempting to create a slide-down animation for my div element using react-spring. However, I am facing an issue where the slide-down effect is not functioning as expected even though I followed a tutorial for implementati ...

Combine two sets of JavaScript objects based on their positions using Underscore.js

Data Set 1: {id: "01", name: "John Doe", age: "25", city: "New York", country: "USA"} Data Set 2: [{key:'id', value:'01'},{key:'name', value:'John Doe'},{key:'age', value:'25'},{key:'city& ...

What is the best way to access a private class variable within the sockent.on function in Angular?

export class AppComponent { title = 'my-app'; constructor(private notifyService : NotificationService) {} ngOnInit() { socket.on("laravel_database_chat:test", function(message){ //I AM ATTEMPTING TO INVOKE THE NOTIF ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

Utilize Android accelerometer data to bring objects to life with animation

Utilizing an Android app, I am streaming accelerometer data to a Python script on my PC. The data is then saved to a text file. My goal is to utilize Javascript and jQuery to animate a 3D CSS cuboid (representing the device) to replicate the movements capt ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

Firebase onSnapshot error when retrieving data from Snapchot

Having trouble with Firebase authentication. Whenever I try to authenticate with Firebase, I encounter this error message: App.js:27 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onSnapshot') Here is the code sni ...

The React apexchart heatmap's height remains static despite attempting to change it through state updates

Seeking to dynamically resize the height of an "Apexcharts heatmap" based on server data. Despite attempting to manipulate code in various lifecycle methods, including componentDidMount() and where the data is received, I have not been successful. Within ...

Achieve a new line break when the user hits the "Enter" key using HTML and JavaScript

I'm in the process of developing a Chrome Extension that allows users to create a to-do list. My goal is to enable users to submit their task by pressing the "Enter" key, which should move the task to the next line after submission. I am currently fac ...

What is the best way to target a specific item in a list using JavaScript in order to modify its appearance?

How can I modify the appearance of a specific li element when it is clicked? ...

Struggling to save a signature created with an HTML5 Canvas to the database

I've been on the hunt for a reliable signature capture script that can save signatures to MySQL, and I finally found one that fits the bill. However, there are two issues that need addressing: The canvas doesn't clear the signature when the c ...

Guide on how to selectively add middleware such as multer to a fresh express router

For a previous project, I set up a router and utilized multer for handling file uploads. I was able to apply the multer middleware selectively on specific routes as shown below: var router = express.Router(); var multer = require('multer'); var ...

Using NPM packages with vanilla JavaScript can be achieved without the need for an HTML file

Is there a way to include an NPM package in my index.js file without installing it via a package manager? I do not have an HTML file, only the index.js file which is executed with 'node index.js' command. Since I cannot use a CDN, is there any me ...

Real estate listing featuring unique symbols

How do I include the ' character in properties when writing my object, like this: const championsList = { Kha'Zi: '...', }; Any suggestions on how to achieve this? ...

How can non-numeric characters be eliminated while allowing points, commas, and the dollar sign?

Looking for an efficient method to filter out all characters except numbers, '$', '.', and ','. Any suggestions on achieving this task? ...

Determining the victorious player in a game of Blackjack

After the player clicks "stand" in my blackjack game, my program checks for a winner. I am using AJAX to determine if there is a winner. If there is a winner, an alert will display their name. Otherwise, the dealer will proceed with making their move. Any ...

Having trouble with Vue's $route.push method not working when invoked from a method?

I am currently in the process of creating a search bar for my application using the vue-bootstrap-typeahead autocomplete library. For those unfamiliar, when an option is selected from the suggestions list, it triggers the @hit event which passes the result ...

Using Props with jQuery in React Components: A Comprehensive Guide

I trust you comprehend this straightforward example. I attempted to modify the background color of my HTML element during initial rendering by managing it in a React Component with a touch of jQuery assistance. Here is the code within my React Component ...

Struggling with implementing jQuery AJAX in Node.js Express - any tips?

Struggling with implementing ajax in node js for the first time. I've been testing it using the console, but unable to get a response. Here's my code: <script> function getMessage() { var data = $("#messageselect").val() $.ajax({ ...