بتل کد Battle Codeدارد باز می‌شود…

جواب «The Garage» چالش 6 از جلسه‌ی 23

سؤال

یک خانواده‌ی کوچک از صفر بنویس.
۱. کلاس Vehicle با سازنده‌ی کوتاه: public name: string و public wheels: number. متد describe(): string متنی مثل Bus has 4 wheels برمی‌گرداند.
۲. کلاس Bike فرزند Vehicle. سازنده‌اش فقط name می‌گیرد و والد را با ۲ چرخ می‌سازد: super(name, 2);
۳. Bike یک متد خودش دارد: ring(): string که Ding! برمی‌گرداند.
۴. Bike متد describe را دوباره می‌نویسد: همان متن والد (با super.describe()) به‌علاوه‌ی and a bell.
۵. تابع park(v: Vehicle): string که Parked: و بعد اسم وسیله را برمی‌گرداند.
برنامه‌ی زیرش:
- const bus = new Vehicle("Bus", 4); و const bike = new Bike("BMX");
- show(bus.describe()); (Bus has 4 wheels)
- show(bike.describe()); (BMX has 2 wheels and a bell)
- show(bike.ring()); (Ding!)
- show(park(bike)); (Parked: BMX)

راهنما

در Vehicle: return this.name + " has " + this.wheels + " wheels";. در Bike: return super.describe() + " and a bell";. چون دوچرخه یک Vehicle است، park(bike) قبول می‌شود.

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
class Vehicle {
  constructor(public name: string, public wheels: number) {}

  describe(): string {
    return this.name + " has " + this.wheels + " wheels";
  }
}

class Bike extends Vehicle {
  constructor(name: string) {
    super(name, 2);
  }

  ring(): string {
    return "Ding!";
  }

  describe(): string {
    return super.describe() + " and a bell";
  }
}

function park(v: Vehicle): string {
  return "Parked: " + v.name;
}

const bus = new Vehicle("Bus", 4);
const bike = new Bike("BMX");
show(bus.describe());
show(bike.describe());
show(bike.ring());
show(park(bike));
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن