A Guide to Listing Private JavaScript Class Properties

What is the best approach to iterate through private class fields?

class Person {
  #isFoo = true;
  #isBar = false;

  constructor(first, last) {
    this.firstName = first;
    this.lastName = last;
  }

  enumerateSelf() {
    console.log(this);
    // (public/private fields shown)

    // iterate through instance fields
    for (let key in this) {
      console.log(key)
      // (only public fields shown)
    }

    // What is the technique to iterate/loop through private fields as well?
  }
}

new Person('J', 'Doe').enumerateSelf();

Answer №1

Unfortunately, it is impossible to access private fields through enumeration as they are not accessible outside the class declaration. They lack a method for enumeration and are not treated as traditional properties. Therefore, there is no dynamic way to access them, as outlined in this discussion.

Your only option is

enumerateSelf() {
    console.log(this);
    for (let key in this) {
        console.log("public", key, this[key]);
    }
    console.log("private isFoo", this.#isFoo);
    console.log("private isBar", this.#isBar);
}

An issue was raised in the private-fields proposal regarding "Private field iteration", but it was clarified by a TC39 member that "Private fields are not properties. You can't reflect on them by design.".

Answer №2

Maybe not the most elegant approach, but one potential solution could involve adjusting your structure to look something like this:

class Individual {
  #traits = {
      isGood: true,
      isBad: false
  };

  constructor(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
  }

  listPrivateAttributes() {
    // loop through private properties
    for (let property in this.#traits) {
      console.log(property)
      // (only displaying public attributes)
    }
  }
}

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

Encountering a Problem with Image Rendering in Next.js

Issue: I am facing a problem while trying to display a react component using <Gallery images={images} />. The component itself is rendered, but the images from the array are not showing up initially. However, when I resize the screen by dragging the ...

Why does the parent URL become the origin for an AJAX request coming from an iframe?

I am facing an issue with a website where I need to load an iframe from a different subdomain. The main website is hosted on portal.domain.com, and the iframe is on iframe.domain.com. To make requests to iframe.domain.com from portal.domain.com, I decided ...

Using radio buttons and a price slider, a unique jQuery filter for products can be

I have successfully implemented basic functionality to filter products based on price (slider) and radio boxes. However, the current filter system uses OR logic, but I need it to use AND instead. For instance, I want to find a product that is from Brand1, ...

Utilizing React, generate buttons on the fly that trigger the display of their respective

Looking for a way to dynamically display 3 buttons, each of which opens a different modal? I'm struggling to figure out how to properly link the buttons to their respective modals. Here's the code I've attempted so far: Button - Modal Code: ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

Ways to effectively hide one window or pop-up upon clicking another

I am working on creating an interactive website for my close circle of friends and family. One of the key features is to have a button that displays their biography when clicked. What I'm aiming for is that when a different bio is selected, the previo ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

Exploring the intricacies of Knockout JS mapping nested models using fromJS function

I am struggling with understanding how to effectively utilize the Knockout JS Mapping Plugin. My scenario involves nested models, and currently I am only using the ko.mapping.fromJS() in the parent model. However, I have noticed that the computed values ar ...

Getting data from a document containing key value pairs

I have a collection of text files that are structured in a key-value pair format. "Site Code": "LEYB" "Also known as": "" "Location": "Pier Site, Poblacion del Sur, Villaba, Southern Leyte" "Contact person(s)": "" "Coordinates[1]": "11 ...

Creating an object using a string in node.js

I have a string that I am sending from AngularJS to NodeJS in the following format. "{↵obj:{↵one:string,↵two:integer↵}↵}" //request object from browser console To convert this string into an object and access its properties, I am using the serv ...

Is there a way to determine if any word within a given text is present in an array?

Imagine you have the following full text: var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy" And a given array like: ["Afghanistan", "Italy", "Albania", "United Arab Emirates"] How can we verify if the exact word Italy within that ent ...

The Socket IO server fails to broadcast a message to a designated custom room

I am currently working on developing a lobby system that allows players to invite each other using Socket io version 4. The process involves the client sending a request to create and join a room, followed by emitting messages to other clients in the same ...

`Formatting Dates with Google Script`

I am looking to modify the date format from "mmm-dd-yyyy" (Nov-11-2019) using my existing code. Here is the code snippet: var timeStamp = data[i][timeStampappr]; var formatted = (timeStamp.getMonth()+1) + '/' + timeStamp.getDate() + &ap ...

Symfony2 does not receive any feedback from the Ajax request

Perform an ajax POST request with no response: Here is the ajax request code snippet: $.ajax({ method: 'POST', url: "{{ path('app-like-add') }}", data: { imageId: id }, success: function(response) { ...

Obtain the current date using Moment JS in JavaScript

Here is a scenario with code : let currentTime = moment(); console.log(currentTime.format()); // 2019-11-25T20:23:50+02:00 console.log(currentTime.toDate()); // 2019-11-25T18:23:50.916Z After applying the timezone change on Heroku using the command ...

Populating a form within an Angular.js application using PhantomJS

Looking to test an AngularJS application using PhantomJS? The first step is to fill in the login form with the username field, assuming there are no other fields involved. Typically, in a real browser, this field is managed by Angular (with the ng-model ...

How can I show a legend entry for every column in Amcharts?

Take a look at this code snippet: http://jsfiddle.net/ouLed1fp/ How can I create a legend entry for each column in the chart? Also, is there a way to display the column names next to them, providing a clear legend? <div id="chartdiv" style="width: 10 ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

What is the importance of having Express in the frontend?

As someone who is relatively new to the world of JavaScript and web applications, I recently came across an Express web application project that contained a public directory, client directory, and server directory. This has raised some questions for me. I ...

The process of batch file conversion and how to effectively utilize it

I am facing an issue with a small batch script that I have been working on. The purpose of this batch script is to execute a Javascript file that converts an XML file to a csv file, followed by running a Python script to analyze the created csv file and ge ...