Cara Membuat Instance di Dalam Class Javascript

Setelah kita membuat class pada JavaScript, lantas bagaimana cara membuat instance dari class tersebut? 

Tapi sebelumnya, apa itu instance? Instance merupakan objek yang memiliki properti dan method yang telah ditentukan oleh blueprint-nya (class), atau singkatnya adalah objek yang merupakan hasil realisasi dari sebuah blueprint.
Sama seperti constructor function, untuk membuat instance dari class pada ES6 kita gunakan keyword new.

  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");


Pembuatan class menggunakan ES6 lebih ketat dibandingkan dengan constructor function, di mana dalam pembuatan instance wajib menggunakan keyword new. Jika kita tidak menuliskannya, maka akan terjadi error 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 = Car("Honda", "Red");

  10.  

  11. /* error:

  12. TypeError: Class constructor Car cannot be invoked without 'new'

  13. */


Kita juga dapat membuat banyak instance dari class yang sama, dan tentunya objek yang kita buat memiliki karakteristik (properti dan method) yang sama. Walaupun sama, namun nilai dari propertinya bersifat unik atau bisa saja berbeda. Contohnya 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. const adamCar = new Car("Tesla", "Black");

  11.  

  12. console.log(johnCar.manufacture);

  13. console.log(adamCar.manufacture);

  14.  

  15. /* output:

  16. Honda

  17. Tesla

  18. */


Variabel johnCar dan adamCar merupakan sebuah objek dari Car. Tentu keduanya akan memiliki properti manufacturecolor, dan enginesActive. Namun pada output kita melihat bahwa nilai dari properti kedua objek tersebut berbeda, karena kita dapat memberikan nilai yang berbeda pada saat objeknya dibuat.

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.