In the absence of producing outcomes, the methods are not generating any

Consider the following scenario:

export class MyClass {
    public dataA = 0
    private dataB = 123
    public myMethod(): any {
        return {
            test: 'true'
        }
    }

    constructor() {
        for (const propOrMethod in this) {
            console.log({propOrMethod})
        }
    }
}

const myInst = new MyClass()

After executing ts-node index.ts, only the following output is displayed:

{ propOrMethod: 'dataA' }
{ propOrMethod: 'dataB' }

Unfortunately, there is no mention of myMethod. It seems like I am unable to iterate through all the methods of my class.

Answer №1

for..in goes through all enumerable properties of the object and up its prototype chain. However, regular methods within a class are not counted as enumerable:

class MyClass {
    myMethod() {
        return {
            test: 'true'
        };
    }
}
console.log(Object.getOwnPropertyDescriptor(MyClass.prototype, 'myMethod').enumerable);

This means they won't be included in iterations. If you need to loop over non-enumerable properties as well, you can utilize Object.getOwnPropertyNames (which loops over the object's own property names, requiring recursive execution for fetching all property names throughout the prototype chain):

const recurseLog = obj => {
  for (const name of Object.getOwnPropertyNames(obj)) {
    console.log(name);
  }
  const proto = Object.getPrototypeOf(obj);
  if (proto !== Object.prototype) recurseLog(proto);
};
class MyClass {
    dataA = 0;
    dataB = 123;
    constructor() {
        recurseLog(this);
    }
    myMethod() {
        return {
            test: 'true'
        };
    }
}
const myInst = new MyClass();

You also have the option of making the method enumerable:

class MyClass {
    dataA = 0;
    dataB = 123;
    constructor() {
         for (const propOrMethod in this) {
            console.log({propOrMethod})
        }
    }
    myMethod() {
        return {
            test: 'true'
        };
    }
}
Object.defineProperty(MyClass.prototype, 'myMethod', { enumerable: true, value: MyClass.prototype.myMethod });
const myInst = new MyClass();

Alternatively, you can assign the method post-class declaration:

class MyClass {
    dataA = 0;
    dataB = 123;
    constructor() {
         for (const propOrMethod in this) {
            console.log({propOrMethod})
        }
    }
}
MyClass.prototype.myMethod = () => ({ test: 'true' });
const myInst = new MyClass();

Or set it to the instance within the constructor:

class MyClass {
    dataA = 0;
    dataB = 123;
    constructor() {
        this.myMethod = this.myMethod;
         for (const propOrMethod in this) {
            console.log({propOrMethod})
        }
    }
     myMethod() {
        return {
            test: 'true'
        };
    }
}
const myInst = new MyClass();

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

How to apply bold formatting to specific words within an array of strings using React and keywords

Imagine you have an array of words that need to be filtered based on a specific keyword and only the top 3 results should be returned. var fruits = ["Banana", "Orange", "Apple", "Mango", "Peach"]; array = array.filter(item => { return item.toLowerC ...

Determining the file size of an HTML and JavaScript webpage using JavaScript

Is there a way to determine the amount of bytes downloaded by the browser on an HTML+JS+CSS page with a set size during page load? I am looking for this information in order to display a meaningful progress bar to the user, where the progress advances bas ...

Navigating Angular with relative paths: A guide to locating resources

Here is the structure of my app: index.html main.ts app |--main.component.html |--main.component.ts |--app.module.ts |--note.png ... etc I am trying to include the note.png file in main.component.html which is located in the same folder. I have att ...

The jQuery click event does not fire within a bootstrap carousel

I am trying to set up a bootstrap carousel where clicking on an image inside it will trigger a self-made lightbox. However, I am facing some issues with the JavaScript code not being triggered with the following syntax: $('html').on("click", ".l ...

Issue with React form not appearing on web browser

I'm having trouble getting the form to show up on the browser. For some reason, the formComponentDict variable is not displaying any of the form steps. Can anyone point me in the right direction? Any assistance would be greatly appreciated. Thank you ...

The statement 'typeof import("...")' fails to meet the requirement of 'IEntry' constraint

When trying to run npm run build for my NextJS 13 app, I encountered the following type error: Type error: Type 'typeof import("E:/myapp/app/login/page")' does not satisfy the constraint 'IEntry'. Types of property 'def ...

Automatically populate a div with content from a file

As I am completely new to the world of HTML, I find myself in need of quickly putting together something for work just as a proof of concept. I apologize if this question has been answered previously, but honestly, I wouldn't even know how to start se ...

How can I display input only when a checkbox is selected? React with Next.js

I'm trying to figure out how to handle this task, but I'm a bit confused on the approach. I would like to display the promo code field only when the checkbox (I have a promo code) is checked. Additionally, it would be ideal to reveal this field ...

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

Implementing an onclick function to initiate a MySQL update query

<?php include_once("db.php"); $result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'"); while($row=mysql_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['ptype'] . "</td>"; echo "<td>" . $row[&apo ...

Execution of a route within another route in Node.js is facing a setback and not being processed as expected

Hey there, I am currently working on a function that includes a route calling the Auth0 API with updated data from the client. The function is running fine, but for some reason, the app.patch() method isn't executing as expected. I'm a bit stuck ...

Angular 4: Transform a string into an array containing multiple objects

Recently, I received an API response that looks like this: { "status": "success", "code": 0, "message": "version list", "payload" : "[{\"code\":\"AB\",\"short\":\"AB\",\"name\":\"Alberta&b ...

Navigating through pop-ups in Chrome: A guide to using Protractor

Currently, I am utilizing Protractor and am faced with the challenge of handling a pop-up from Chrome. My goal is to successfully click on the button labeled "Open magnet URI". For a visual representation of the issue, refer to the following image: picture ...

Error occurs when a class contains a static member with the name `name`

Within my TypeScript code, I have a simple class named Foo as part of the Test module. module Test { "use strict"; class Foo { public static name = "foo"; } } However, when I attempt to run this code in Chrome, an error occurs: I ...

What is the method for handling a get request in Spring3 MVC?

Within the client side, the following JavaScript code is used: <script src="api/api.js?v=1.x&key=abjas23456asg" type="text/javascript"></script> When the browser encounters this line, it will send a GET request to the server in order to r ...

What potential side-effects could occur from cloning the entire state object in React?

Upon reviewing a React code base I'm currently working on, I've noticed a recurring pattern that concerns me regarding potential bugs. Here is an example of the code in question: const newState = Object.assign({}, {}, this.state); newState.x = ...

Redirecting to a blank homepage using PHP

Having trouble with this code. After logging in, I'm not redirected to the home page, but instead, I stay on the login page. I want users to be redirected to (http://localhost/trial/index.php#Home) once successfully logged in. How can I fix this? < ...

"Fetching and Utilizing the Output Parameter from an API in Angular4: A Step-by-Step Guide

Working on a post method in an Angular 4 web app, I am able to save data to the database successfully. However, I am facing an issue where an ID (return value) is passed from the DB to the API for Angular as another function parameter. How can I retrieve t ...

Utilizing a filter within the ng-model directive

I have a question about using a filter with an h3 element. Here is the code snippet: {{ event.date | date:'dd-MM-yyyy' }} It's working perfectly fine and Angular is formatting the date as expected. However, when I try to use the same filte ...

"Experience the power of Vue.js 3.2 with Dynamic Component Knockout

I am trying to use a dynamic component to update my section, but when I click on my sidebar ('nav'), it doesn't change. Even though route.params.current changes, the component is not loaded. <template> <q-page class="contain ...