Untuk menambahkan method pada class, kita juga cukup menuliskannya pada body class, tidak mesti melalui prototype seperti memakai constructor function.
-
- class Car {
-
- constructor(manufacture, color) {
-
- this.manufacture = manufacture;
-
- this.color = color;
-
- this.enginesActive = false;
-
- }
-
- startEngines() {
-
- console.log(“Mesin dinyalakan”);
-
- this.enginesActive = true;
-
- }
-
- 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 memakai class, meskipun kita menuliskan method pada body class, tetapi method itu tetap berada di prototype chain punyai instance yang terbuat. Kita dapat melihat bagaimana objek yang dibuat memakai class pada console browser.