Node.js
Quiz modeli
Question ve Quiz sınıflarının iskeletini tasarlarsın.
Proje: Quiz uygulaması
Bu 5 derslik projede bir quiz uygulaması yapacaksın. Önce Question sınıfını tanımlayacağız, sonra Quiz sınıfını aşama aşama büyüteceğiz ve son derste bir Express API ile birleştireceğiz.
Bir Question nesnesi üç özellik taşır: id (sıra numarası), text (soru metni) ve answer (doğru yanıt). JavaScript'te sınıf tanımlamanın yolu class anahtar sözcüğüdür. Örnek: class Question { constructor(id, text, answer) { this.id = id; ... } }. constructor yeni bir nesne oluşturulduğunda çağrılır ve özellikleri atar. Her dersin başlangıç kodu önceki dersin çözümünü içerecek.
this ile özellik atama
Sınıf içinde this geçerli nesneyi temsil eder. this.id = id; ataması, kurucu parametreyi nesnenin özelliği yapar. Örnek: constructor(id, text, answer) { this.id = id; this.text = text; this.answer = answer; }.
Bu atamadan sonra new Question(1, "Başkent?", "Ankara") ile oluşturulan nesnede q.id 1, q.text "Başkent?", q.answer "Ankara" olur. this olmadan atanan değişken nesneye değil, yalnızca kurucu içindeki yerel değişkene ayarlanır. Bu yüzden sınıf özellikleri her zaman this ile atanır. Bu, JavaScript sınıflarının temel ilkesidir.
Uygulama Question sınıfını tanımla
class Question tanımla: constructor(id, text, answer) gövdesi this.id = id; this.text = text; this.answer = answer;. const q = new Question(1, "Başkent?", "Ankara") ile nesne oluştur. console.log(q.text) ve console.log(q.answer) ile yazdır.
Örnek çözümü göster
class Question {
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.answer = answer;
}
}
const q = new Question(1, "Başkent?", "Ankara");
console.log(q.text);
console.log(q.answer);
Kendini test et
-
Question sınıfında constructor ne zaman çağrılır?
const q = new Question(1, "Soru?", "Cevap");
- Sınıf tanımlandığında
- new ile nesne oluşturulduğunda
- Program başladığında
- console.log çağrıldığında
Cevabı göster
new ile nesne oluşturulduğunda — constructor, new ile yeni nesne oluşturulduğunda çağrılır.
-
constructor gövdesini tamamla
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.____ = answer;
}
Cevabı göster
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.answer = answer;
}
-
Parçayı rolüne eşle
- class
- Sınıf tanımlar
- constructor
- Yeni nesneyi başlatır
- this
- Geçerli nesneyi temsil eder
- new
- Nesne oluşturur
Sıradaki ders: Soru ekleme