Senin, 27 April 2020

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.     
  •     info() {

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

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

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

  •     }

  • }

  •  

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

  •  

  • johnCar.startEngines();

  • johnCar.info();

  •  

  •  

  • /* output:

  • Mesin dinyalakan

  • Manufacture: Honda

  • Color: Red

  • Engines: Active

  • */


  • 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

    Related Posts

    0 komentar

    Posting Komentar