JS OOP: 21. Class: private field

by istiq20

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Class: private field</title>
  </head>
  <body>
    <script>
      class Counter {
        // private field (hanya bisa diakses didalam class)
        #counter = 0;

        increment() {
          this.#counter++;
        }

        decrement() {
          this.#counter--;
        }

        get() {
          return this.#counter;
        }
      }

      const counter = new Counter();

      counter.increment();
      counter.increment();
      counter.increment();
      counter.increment();
      counter.increment();

      console.info(counter.get()); // 5

      //jika kita coba akses dari luar class
      counter.counter = 100;
      console.info(counter); // tidak mengubah nilai #counter

      // counter.#counter = 100; // Error
    </script>
  </body>
</html>