Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

الميثودات التي تعدل الحالة

جزء من قسم Object Oriented Programming في رحلة JavaScript على Coddy. الدرس 15 من 56.

يمكن للأساليب (Methods) في أصناف JavaScript تعديل حالة (خصائص) الكائن. وتعد هذه إحدى الميزات الرئيسية للبرمجة كائنية التوجه (object-oriented programming).

لنقم بإنشاء فئة BankAccount بسيطة:

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

الآن لنقم بإنشاء مثيل (instance) وتعديل حالته:

const johnsAccount = new BankAccount("John", 100);
console.log(johnsAccount.balance); // المخرجات: 100

johnsAccount.deposit(50);
console.log(johnsAccount.balance); // المخرجات: 150

في هذا المثال، تقوم الطريقة deposit() بتعديل الحالة الداخلية (الخاصية balance) لمثيل BankAccount.

يمكننا إضافة المزيد من الطرق التي تعدل الحالة:

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;
    }
  }
}

الآن يمكننا التعامل مع حسابنا البنكي بطرق متعددة.

challenge icon

التحدي

لقد تم تزويدك بفئة Thermostat. مهمتك هي إضافة دوال (methods) تقوم بتعديل حالة درجة الحرارة الخاصة بها:

  1. increaseTemp() - تزيد درجة الحرارة بمقدار درجة واحدة
  2. decreaseTemp() - تنقص درجة الحرارة بمقدار درجة واحدة

جرّب بنفسك

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

// كود الاختبار - لا تقم بالتعديل
const livingRoom = new Thermostat("Living Room", 20);

livingRoom.increaseTemp();
livingRoom.increaseTemp();
console.log(livingRoom.currentTemp); // يجب أن تكون النتيجة 22

livingRoom.decreaseTemp();
console.log(livingRoom.currentTemp); // يجب أن تكون النتيجة 21
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس Object Oriented Programming

تدرّب بنفسك: مترجم JavaScript عبر الإنترنت