Property Accessor didalam Object Class Javascript

Melalui objek class kita juga dapat mengubah nilai properti seperti ini:


  1. class Car {

  2.     constructor(manufacture, color) {

  3.         this.manufacture = manufacture;

  4.         this.color = color;

  5.         this.enginesActive = false;

  6.     }

  7. }

  8.  

  9. const johnCar = new Car("Honda", "Red");

  10. console.log(`Warna mobil: ${johnCar.color}`); // output -> Warna Mobil: Red

  11.  

  12. johnCar.color = "White"; // Mengubah nilai properti color menjadi white

  13.  

  14. console.log(`Warna mobil: ${johnCar.color}`); // output -> Warna Mobil: White


Dengan class kita juga dapat mengimplementasi getter/setter sebuah properti menjadi sebuah method seperti ini:

  1. class Car {

  2.     constructor(manufacture, color) {

  3.         this.manufacture = manufacture;

  4.         this._color = color;

  5.         this.enginesActive = false;

  6.     }

  7.     

  8.     get color() {

  9.         return `Warna mobile ${this._color}`;

  10.     }

  11.     

  12.     set color(value) {

  13.         console.log(`Warna mobil diubah dari ${this._color} menjadi ${value}`);

  14.         this._color = value;

  15.     }

  16. }

  17.  

  18. const johnCar = new Car("Honda", "Red");

  19. console.log(johnCar.color); // output -> Warna Mobil: Red

  20. johnCar.color = "White"; // Mengubah nilai properti color menjadi white

  21. console.log(johnCar.color); // output -> Warna Mobil: White


Perhatikan juga ketika kita menerapkan getter/setter pada properti class. Kita perlu mengubah atau membedakan penamaan properti aslinya dengan property accessor yang kita buat. Berdasarkan code convention yang ada kita perlu mengubah properti asli class-nya dengan menambahkan underscore di depan nama propertinya (_color). Tanda underscore berfungsi sebagai tanda bahwa properti _color tidak sebaiknya diakses langsung, namun harus melalui property accessor (getter/setter)

About the Author

Saya seorang lulusan SMK

Posting Komentar


Cookie Consent
Ikramlink.com serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.