JS OOP: 19. Class: getter dan setter

by istiq20

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Class: getter dan setter</title>
  </head>
  <body>
    <script>
      class Person {
        constructor(firstName, lastName) {
          this.firstName = firstName;
          this.lastName = lastName;
        }

        // getter dan setter berada di prototype
        get fullName() {
          return ` Fullname: ${this.firstName} ${this.lastName}`;
        }

        set fullName(value) {
          const result = value.split(" ");
          this.firstName = result[0];
          this.lastName = result[1];
        }
      }

      const eko = new Person("Eko", "Khannedy");
      console.info(eko);
      console.info(eko.fullName); // Fullname: Eko Khannedy

      eko.fullName = "Budi Nugraha";
      console.info(eko); // Fullname: Budi Nugraha
    </script>
  </body>
</html>