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

Exploring the use of the Next.js page router for implementing internationalization (i18

I need assistance implementing Dutch and English language translations for my entire website. Can anyone provide guidance? I have tried using i18n localizely, but it only works for individual pages. I am looking to implement translations on a larger scale ...

Can you use an ajax post to search for a boolean in MongoDB without converting on the server side?

I am facing an issue with my mongo collection that has documents containing a boolean field: { name : "Tom", active : true } { name : "Jerry", active : false } In my application's client side, there is an element that triggers an AJAX po ...

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...

Issue with the usage of section helpers in express-handlebars

I'm having trouble getting the section helper to function correctly. The content of login.hbs was parsed properly, but the js section was not parsed at all. I attempted using helpers within res.render() and directly including section() in engine(), bu ...

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...

ExtJS web displays appear differently when viewed on Chrome's toggle device mode versus a mobile browser

Greetings, I have been working on developing a web application that can be accessed through a mobile browser. Initially, I created the web application and tested it in mobile mode using Chrome's simulation feature. However, when I tried accessing th ...

Node.js route does not support io.sockets.on functionality

Incorporating io.sockets.on into a route within a Node.js and Express application is proving to be challenging. I have been following the guidance provided here: While I am able to successfully send io.sockets.emit events, I am encountering an issue with ...

Mastering universal code creation with the composition API in Quasar

The Quasar website explains that for writing universal code, the created and beforeCreate lifecycle hooks in Vue components are executed in Server Side Rendering (SSR). This raises a question: What about setup? How can I achieve SSR functionality with th ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

When using CasperJS to capture multiple screenshots, the most recent screenshot will replace all previous ones

Exploring CasperJS has been a great experience for me. Despite my enjoyment, I've encountered an issue with casper.capture() that has me stumped. I've set it up to capture screenshots whenever a test fails and placed it in a separate setup module ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

Alter the value of a key within a JSON object at a specific nested level using Node.js or JavaScript

I am attempting to swap out a specific value in the JSON file. Let's say the JSON data provided below: sample.json let sample={ "yuiwedw":{ "id":"yuiwedw", "loc": "ar", "body":{ "data":"we got this", "loc":"ar", "system":{ ...

jQuery is unable to manipulate newly added DOM elements that have been loaded via AJAX

Having trouble with jquery ajax. Unable to interact with newly added element through ajax. Code snippet: $(".yorum_input").keypress(function(e) { if (e.keyCode == 13) { e.preventDefault(); var alt_id = $(this).attr('yorum_id'); va ...

Changing the color of a placeholder using Javascript: A step-by-step guide

I've been searching online without any luck so far. I'm attempting to change the placeholder color of a text box using JavaScript, but I'm not sure how to go about it. I already have a color picker that changes colors. If my CSS looks somet ...

Issue with e2e.js file format in Cypress Support

I am trying to save Cypress screenshots into a report using a support file as recommended in the documentation. However, I keep encountering an error: Your supportFile is missing or invalid: support/e2e.js The supportFile must be a .js, .ts, .coffee file ...

I'm looking to customize my d3.js Bar Graph by changing the color of each bar individually and adding a Scale for them. How can I

I am currently working on constructing a graph that illustrates the data for the Amount of Resources utilized Per Project by creating a bar graph. I am aiming to customize the colors of the bars so that each one has its own unique color. Currently, the col ...

Verify if the ajax request does not contain any data

Utilizing the complimentary geocoding API provided by MapQuest I'm attempting to verify the success of a request that returned no data. Entering "vdfsbvdf54vdfd" (a nonsensical string) as an address in a form field, I anticipate receiving an alert s ...

Utilizing Piwik Analytics in jQuery Mobile Framework

Having an issue with tracking users on my mobile Web App using Piwik. Due to AJAX, only views on the first page are being tracked. I attempted to use the pageinit function to load the Piwik tracking script on every page, but it still only tracks the firs ...

Tips for creating a non-blocking sleep function in JavaScript/jQuery

What is the best way to create a non-blocking sleep function in JavaScript or jQuery? ...