topskill.dev
CoursesTracks
0
All courses/Introduction to JavaScriptInheritance
Object-Oriented Programming
6 / 11
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking○Missing values and deliberate emptiness○Inspect Values in the Console○Inspect the Queue Report○Trace a Faulty Calculation○Repair the Score Calculation✦Module Quiz
○Declaring Variables○let and const in Practice○Operators○Type Conversion○Group and Convert Expense Inputs○Calculate the Event Expense Total○Track a Changing Points Tally○Adjust a Ticket Price✦Module Quiz
○Comparisons and strict equality○Truthiness and combined conditions○Function inputs and results○Conditionals○Combined Conditions Before FizzBuzz○Challenge: FizzBuzz Announcer○Switch Statement○Switch a Venue Sign○Challenge: Power Loadout○For Loops○While Loop○Break and Continue○Stop a Ticket Scan○Challenge: Number Guess Referee○Rainfall Routing Walkthrough○Score Batch Report✦Module Quiz
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions○Ticket Pricing Walkthrough○Shipping Labels with Defaults○Seat Ledger Closure Walkthrough○Private Budget Ledger✦Module Quiz
○Arrays○Student Scoreboard○Challenge: Student Course Scoreboard○Array Mutation Methods○Array Slice and Concat○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every○Charging Rack Restock Report○Pantry Restock Plan✦Module Quiz
○Object Key-Value Pairs○Student Course Record○Object Methods and Destructuring○Object copies and optional properties○Map and Set Collections○Playlist Lookup○Number and BigInt Boundaries○Ticket Ledger○JSON○Throwing and catching errors○Math and Date○Date Basics○Supply Bin Audit○Volunteer Shift Audit○Workshop Attendance Feed○Parcel Scan Feed✦Module Quiz
○String Methods○Template Literals○Regular Expressions○Build a Reminder with Template Literals○Format Pantry Pickup Messages○Validate a Time Slot with Regex○Validate Storage Shelf Labels✦Module Quiz
○Higher-Order Functions○Callbacks○map, filter, and reduce○Student Register with map○Challenge: Student Register○Recursion○Project - Data Transform Pipeline○Extend the inventory report○Handle an Error-First Callback○Report Seat Reservation Results○Summarize Completed Bike Rides○Summarize Delivered Parcels✦Module Quiz
○A notebook object○OOP Introduction○Independent workshop passes○Classes○An inherited notice●Inheritance○A private seat counter○Encapsulation○Equipment desk checkout○Project: Library Checkout✦Module Quiz
○Callback Timing○Asynchronous JavaScript○Promise Rehearsal○Promises and Async Await○Offline API Coordination○Async API Simulation○Partial Results Bulletin○Project: Resilient Awards Feed○Retry a Local Delivery○Project: Reliable Score Delivery✦Module Quiz

Inheritance

Give circles and rectangles a shared color property while letting each calculate its own area. The notice demo showed how a child constructor initializes the inherited part with super.

Store dimensions on each instance, not in fixed output strings. Circle area is Math.PI * radius ** 2. To return a number rounded to two decimal places, multiply by 100, round with Math.round, then divide by 100. Rectangle area is width times height.

The Dog example below has no constructor of its own; JavaScript supplies a derived constructor that forwards arguments to the parent. If you write your own derived constructor, as the exercise does, you must call super yourself before accessing this. The supplied tryCreate helper catches errors from unfinished constructors so the Shape task can be checked first. Its ?. probes display missing values rather than stopping the script.

Basic inheritance

javascript
class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        return `${this.name} makes a sound.`;
    }

    toString() {
        return `Animal(${this.name})`;
    }
}

class Dog extends Animal {
    speak() {
        return `${this.name} barks.`;
    }
}

class Cat extends Animal {
    speak() {
        return `${this.name} meows.`;
    }
}

const dog = new Dog("Rex");
console.log(dog.speak());
console.log(dog.toString());

Calling the parent with super

This snippet continues with the Animal class above.

javascript
class TaggedAnimal extends Animal {
    constructor(name, tag) {
        super(name); // initialize the Animal before using this
        this.tag = tag;
    }
    toString() { return `${super.toString()} #${this.tag}`; }
}
console.log(new TaggedAnimal("Rex", 5).toString()); // Animal(Rex) #5

instanceof check

These expressions use the same dog, Dog, Animal, and Cat from the first example. The comments show returned values; an expression alone does not print a Console line.

javascript
dog instanceof Dog;     // true
dog instanceof Animal;  // true — Dog IS an Animal
dog instanceof Cat;     // false

Edit script.js, then use Run to inspect the supplied checkpoints. Use Submit to check your tasks in order. Keep the supplied probes; change only the requested definitions and final logs.

Your Task

  1. Store the supplied color in Shape; the default is "black".
  2. Initialize Circle by calling super(color) before storing radius.
  3. Return the circle area rounded to two decimal places from area().
  4. Return Circle(radius: R, color: C, area: A) from toString() using the instance values and its area method.
  5. Initialize Rectangle by calling super(color) before storing width and height.
  6. Return width times height from Rectangle.area().
  7. Return Rectangle(W×H, color: C, area: A) from its toString() using instance values.
  8. Log the two descriptions, joined by | and prefixed with mission result: .
Hint 1
1 / 3
HINT 1

Use extends to inherit: class Child extends Parent {}

HINT 2

Call super(args) inside the child constructor before using this.

HINT 3

Override a parent method by defining it again in the child class.

Files
  • ⋄script.js
Loading editor…
Press Run to execute your code.