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

A simple example of private class features is in the 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 the parent class in JavaScript?

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

Note: Private fields are a part of the ECMAScript standard and may not be supported in older browsers. Always check the compatibility table to ensure that the features you are using are supported in the target environments.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading