constructor ve instance
constructor ile yeni bir örnek oluşturmayı ve new operatörünü öğrenirsin.
constructor nedir?
constructor (yapıcı yöntem), bir sınıftan yeni örnek oluşturulduğunda çalışan özel bir yöntemdir. Adı her zaman constructor'dır ve genelde örneğin başlangıç özelliklerini atar.
class User {
constructor(name) {
this.name = name;
}
}Buradaki this, yeni oluşturulan örneği işaret eder; this.name örneğe bir özellik ekler.
new operatörü
Bir örnek üretmek için new operatörünü kullanırsın: const u = new User("Ayşe");. Bu ifade şunu yapar:
- Yeni boş bir nesne oluşturur.
constructor'ı çağırır vethis'i bu nesneye bağlar.- Oluşan nesneyi döndürür.
Sonuç, u değişkenine atanan bir örnek (instance)'tir.
Uygulama Ürün sınıfı
Bir Product sınıfı tanımla. Yapıcısı name ve price parametrelerini alıp this.name ve this.price özelliklerine atasın.
Örnek çözümü göster
Yapıcı içinde this.name = name ve this.price = price yaz.
Örnek çözüm:
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
Kendini test et
-
`new User("Ayşe")` ifadesi ne döndürür?
new User("Ayşe")- bir sınıf
- bir yöntem
- bir özellik
- bir örnek
Cevabı göster
bir örnek — Doğru! new operatörü sınıfın yeni bir örneğini döndürür.
-
Yeni örnek oluştur
const u = ____;Cevabı göster
const u = new User(); -
Kavramları eşleştir
- constructor
- yapıcı yöntem
- new
- yeni örnek operatörü
- this
- oluşturulan örneği işaret eder
- instance
- sınıftan üretilen nesne