Lompat ke konten Lompat ke sidebar Lompat ke footer

Cara Menambahkan Method didalam Class Javascript

Untuk menambahkan method pada class, kita juga cukup menuliskannya pada body class, tidak perlu melalui prototype seperti menggunakan constructor function.

  1. class Car {

  2.     constructor(manufacture, color) {

  3.         this.manufacture = manufacture;

  4.         this.color = color;

  5.         this.enginesActive = false;

  6.     }

  7.     

  8.     startEngines() {

  9.         console.log("Mesin dinyalakan");

  10.         this.enginesActive = true;

  11.     }

  12.     

  13.     info() {

  14.         console.log(`Manufacture: ${this.manufacture}`);

  15.         console.log(`Color: ${this.color}`);

  16.         console.log(`Engines: ${this.manufacture ? "Active" : "Inactive"}`);

  17.     }

  18. }

  19.  

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

  21.  

  22. johnCar.startEngines();

  23. johnCar.info();

  24.  

  25.  

  26. /* output:

  27. Mesin dinyalakan

  28. Manufacture: Honda

  29. Color: Red

  30. Engines: Active

  31. */


Dengan menggunakan class, walaupun kita menuliskan method pada body class, namun method tersebut tetap berada pada prototype chain miliki instance yang terbuat. Kita bisa melihat bagaimana objek yang dibuat menggunakan class pada console browser
20200312163128914b6b721efd67a21c9e124a0111699e.gif

Posting Komentar untuk "Cara Menambahkan Method didalam Class Javascript"