Menu
Coddy logo textTech

Durumu değiştiren metotlar

Coddy'nin JavaScript Journey'sinin Nesne Yönelimli Programlama bölümünün bir parçası — ders 15 / 56.

JavaScript sınıflarındaki metotlar, bir nesnenin durumunu (özelliklerini) değiştirebilir. Bu, nesne yönelimli programlamanın temel özelliklerinden biridir.

Basit bir BankAccount sınıfı oluşturalım:

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  
  deposit(amount) {
    this.balance += amount;
  }
}

Şimdi bir örnek oluşturalım ve durumunu değiştirelim:

const johnsAccount = new BankAccount("John", 100);
console.log(johnsAccount.balance); // Çıktı: 100

johnsAccount.deposit(50);
console.log(johnsAccount.balance); // Çıktı: 150

Bu örnekte, deposit() metodu BankAccount örneğinin dahili durumunu (balance özelliği) değiştirir.

Daha fazla durum değiştiren metot ekleyebiliriz:

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  
  deposit(amount) {
    this.balance += amount;
  }
  
  withdraw(amount) {
    if (amount <= this.balance) {
      this.balance -= amount;
    }
  }
  
  transfer(amount, toAccount) {
    if (amount <= this.balance) {
      this.balance -= amount;
      toAccount.balance += amount;
    }
  }
}

Artık banka hesabımızı birden fazla şekilde yönetebiliriz.

challenge icon

Görev

Size bir Thermostat sınıfı verilmiştir. Göreviniz, sıcaklık durumunu değiştiren metotlar eklemektir:

  1. increaseTemp() - sıcaklığı 1 derece artırır
  2. decreaseTemp() - sıcaklığı 1 derece azaltır

Kopya kağıdı

JavaScript sınıflarındaki metotlar, bir nesnenin durumunu (özelliklerini) değiştirebilir.

Durum değiştiren metotlara sahip bir sınıf örneği:

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  
  deposit(amount) {
    this.balance += amount;
  }
  
  withdraw(amount) {
    if (amount <= this.balance) {
      this.balance -= amount;
    }
  }
  
  transfer(amount, toAccount) {
    if (amount <= this.balance) {
      this.balance -= amount;
      toAccount.balance += amount;
    }
  }
}

Durum değiştiren metotların kullanımı:

const johnsAccount = new BankAccount("John", 100);
console.log(johnsAccount.balance); // Çıktı: 100

johnsAccount.deposit(50);
console.log(johnsAccount.balance); // Çıktı: 150

Kendin dene

import { Thermostat } from './thermostat.js';

// Test kodu - değiştirmeyin
const livingRoom = new Thermostat("Living Room", 20);

livingRoom.increaseTemp();
livingRoom.increaseTemp();
console.log(livingRoom.currentTemp); // 22 çıktısını vermeli

livingRoom.decreaseTemp();
console.log(livingRoom.currentTemp); // 21 çıktısını vermeli
quiz iconKendini test et

Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.

Nesne Yönelimli Programlama bölümündeki tüm dersler