Özet - Nesneler
Nesne ve metotlarını kullanarak bir banka hesabı uygulaması yazarsın.
Özet - Banka hesabı
Bu derste nesneleri, özellikleri, metotları ve this'i birleştirerek basit bir banka hesabı uygulaması yazacağız. Hesap nesnesi bakiyeyi tutar ve deposit ile withdraw metotlarıyla para ekleyip çekmeyi sağlar.
const account = {
owner: 'Ayşe',
balance: 0
};Önce hesabı oluşturup para yatıracağız, sonra çekme metodunu ekleyeceğiz. Her adımda this.balance ile aynı nesnenin bakiyesini güncelleyeceğiz.
Uygulama Banka hesabı oluştur
account adında bir nesne oluştur. owner özelliği 'Ayşe', balance özelliği 0 olsun. Kısa yazım ile deposit metodu tanımla: amount parametresi al, this.balance'a ekle ve yeni bakiyeyi döndür. Sonra console.log(account.deposit(100)) ile çağır.
Örnek çözümü göster
const account = {
owner: 'Ayşe',
balance: 0,
deposit(amount) {
this.balance = this.balance + amount;
return this.balance;
}
};
console.log(account.deposit(100));
Uygulama withdraw metodu ekle
Aşağıdaki account nesnesine withdraw metodu ekle. amount parametresi al, this.balance'dan çıkar ve yeni bakiyeyi döndür. Sonra console.log(account.withdraw(30)) ile çağır.
Örnek çözümü göster
const account = {
owner: 'Ayşe',
balance: 100,
deposit(amount) {
this.balance = this.balance + amount;
return this.balance;
},
withdraw(amount) {
this.balance = this.balance - amount;
return this.balance;
}
};
console.log(account.withdraw(30));
Kendini test et
-
deposit metodu this.balance'i nasıl günceller?
deposit(amount) { this.balance = ?; }- balance + amount
- this + amount
- this.balance + amount
- amount
Cevabı göster
this.balance + amount — Doğru! this.balance + amount yeni bakiyeyi verir.
-
deposit metodunu tamamla
deposit(amount) { this.balance = this.balance ____ amount; return this.balance; }Cevabı göster
deposit(amount) { this.balance = this.balance + amount; return this.balance; } -
Kavramları eşleştir
- { }
- nesne literali
- user.name
- nokta notasyonu
- this.balance
- metot içinde erişim