skip to Main Content

In the following code:

class Foo {
  #a;
  #b = 123;
  c = 3.14;

  tellYourself() {
    console.log("OK the values are", JSON.stringify(this));
  }
}

const foo = new Foo();

foo.tellYourself();

Only this is printed:

OK the values are {"c":3.14}

Is there a way to print out all properties automatically, including the private ones?

(meaning if there are 25 private variables, print all of them out automatically, instead of specifying them one by one?).

2

Answers


  1. In JavaScript, private class fields (denoted by the # symbol) cannot be accessed or enumerated outside of the class itself. They are intentionally designed to be inaccessible from outside the class for encapsulation and data privacy purposes.

    However, it would be possible if you explicitly point to this fields.

    class Foo {
      #a;
      #b = 123;
      c = 3.14;
    
      getAllProperties() {
        return {
          c: this.c,
          '#a': this.#a,
          '#b': this.#b
        };
      }
    
      tellYourself() {
        console.log("All properties:", this.getAllProperties());
      }
    }
    
    const foo = new Foo();
    
    foo.tellYourself();
    Login or Signup to reply.
  2. It is impossible.

    The only way to access a private property is via dot notation, and you can only do so within the class that defines the private property.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties

    So I can suggest you to redesign your solution according to your goal.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search