Skip to content

JavaScript private fields | Class

  • by

There is no native support for private fields/properties with JavaScript (ES6) classes.But you can prefix the name with # and include it in the class definition, not just the constructor.

Real private properties were finally added in ES2022. As of 2022-03-22, private properties (fields and methods) have been supported in all major browsers for at least six months, but 10-20% of users are still on older browsers.

Source: stackoverflow.com

JavaScript private fields

Simple example private class features is in Stage 3 proposal. The majority of its features are supported by all major browsers.

<!DOCTYPE html>
<html>
<body>
  <script>

    class Something {
      #property;

      constructor(){
        this.#property = "test";
      }

      #privateMethod() {
        return 'hello world';
      }

      getPrivateMessage() {
        return this.#property;
      }
    }

    const instance = new Something();
    console.log(instance.property); //=> undefined
    console.log(instance.privateMethod); //=> undefined
    console.log(instance.getPrivateMessage()); //=> test
    console.log(instance.#property); //=> Syntax error

  </script>

</body>
</html> 

Output:

JavaScript private fields

How to access private fields from parent class in JavaScript?

Answer: This is not possible. Private really means private in JS. Don’t use it if you want the field to be accessible outside of the class.

Do comment if you have any doubts or suggestions on this JS filed topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *