JavaScript Inheritance with extends and super (Classes)

Inheritance lets one class build on another: a LoginPage and a CartPage can both inherit open(), waitForLoad() and a header component from a shared BasePage, and add only what is specific to them. In this lesson you will learn how extends and super work, how to override and extend methods, how static members and built-in classes such as Error are inherited, and when composition is a better choice than a deep class hierarchy.

Advertisement

📖 What You’ll Learn: what inheritance is, extends, calling the parent constructor with super(), the “must call super before this” rule, inherited methods and fields, overriding methods, calling the parent version with super.method(), inherited static members, instanceof with subclasses, extending built-ins such as Error and Array, abstract-style base classes, and composition versus inheritance.


🌳 What Is Inheritance?

Definition: inheritance means a class (the child, subclass or derived class) automatically gets the properties and methods of another class (the parent, superclass or base class). The child can add new members and change inherited ones. In JavaScript you write it with extends.

📄 extends.js

class Animal {
  constructor(name) {
    this.name = name;
  }
  describe() {
    return `${this.name} is an animal`;
  }
}

class Dog extends Animal {
  bark() {
    return `${this.name} says woof`;
  }
}

const rex = new Dog("Rex");
console.log(rex.describe());       // inherited from Animal
console.log(rex.bark());           // defined in Dog
console.log(rex instanceof Dog, rex instanceof Animal);

⌨️ Terminal

node extends.js

🖥️ Output

Rex is an animal
Rex says woof
true true

Dog has no constructor of its own, so JavaScript uses a default one that passes all arguments to the parent constructor.


🔼 super(): Calling the Parent Constructor

When a child class defines its own constructor, it must call super(...) to run the parent constructor before it uses this:

📄 super-constructor.js

class Employee {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
}

class Tester extends Employee {
  constructor(name, email, tools = []) {
    super(name, email);        // the parent sets name and email
    this.tools = tools;        // then the child adds its own property
  }
}

const asha = new Tester("Asha", "asha@sqatools.in", ["Playwright", "Postman"]);
console.log(asha);

⌨️ Terminal

node super-constructor.js

🖥️ Output

Tester {
  name: 'Asha',
  email: 'asha@sqatools.in',
  tools: [ 'Playwright', 'Postman' ]
}

Using this before super() is an error, because the object is created by the parent constructor:

📄 super-first.js

class Base {}
class Broken extends Base {
  constructor() {
    this.x = 1;      // too early
    super();
  }
}
try {
  new Broken();
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node super-first.js

🖥️ Output

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

🔁 Overriding Methods and super.method()

Definition: overriding means a child class defines a method with the same name as a parent method, replacing it for child instances. Inside the override, super.method() calls the parent version, so you can extend its behaviour instead of rewriting it.

📄 override.js

class Report {
  constructor(title) {
    this.title = title;
  }
  header() {
    return `=== ${this.title} ===`;
  }
  render(lines) {
    return [this.header(), ...lines].join("\n");
  }
}

class CiReport extends Report {
  header() {                                  // override
    return `${super.header()} (CI build #4512)`;   // extend the parent version
  }
}

console.log(new Report("Smoke").render(["12 passed"]));
console.log(new CiReport("Smoke").render(["12 passed"]));

⌨️ Terminal

node override.js

🖥️ Output

=== Smoke ===
12 passed
=== Smoke === (CI build #4512)
12 passed

Notice that render is defined only in Report, yet it calls the child’s header() for a CiReport. Method lookup always starts from the actual object, which is the core of polymorphism (lesson 42).


Advertisement

📋 Inherited Fields and Static Members

Class fields and static members are inherited too. Static methods are called on the child class and can be overridden in the same way:

📄 statics.js

class BaseClient {
  static defaultTimeout = 30000;
  retries = 0;

  static create(baseURL) {
    return new this(baseURL);      // "this" is the class it was called on
  }
  constructor(baseURL) {
    this.baseURL = baseURL;
  }
}

class PaymentsClient extends BaseClient {
  static defaultTimeout = 60000;   // override the static field
  retries = 2;                     // override the field default
}

const base = BaseClient.create("https://api.qa");
const pay = PaymentsClient.create("https://pay.qa");
console.log(base.constructor.name, base.retries, BaseClient.defaultTimeout);
console.log(pay.constructor.name, pay.retries, PaymentsClient.defaultTimeout, pay instanceof BaseClient);

⌨️ Terminal

node statics.js

🖥️ Output

BaseClient 0 30000
PaymentsClient 2 60000 true

new this(...) inside a static method creates an instance of whichever class the method was called on, so the inherited create returns a PaymentsClient.


🔗 The Prototype Chain Behind extends

extends sets up two prototype links: instances of the child inherit from the parent’s prototype, and the child class itself inherits from the parent class (for static members). It is the same mechanism you saw in the Prototypes lesson:

📄 chain.js

class A { hello() { return "hello from A"; } }
class B extends A {}
const b = new B();

console.log(Object.getPrototypeOf(b) === B.prototype);
console.log(Object.getPrototypeOf(B.prototype) === A.prototype);   // instance chain
console.log(Object.getPrototypeOf(B) === A);                       // static chain
console.log(Object.hasOwn(B.prototype, "hello"), b.hello());

⌨️ Terminal

node chain.js

🖥️ Output

true
true
true
false hello from A

⚠️ Extending Built-ins: Custom Errors

You can extend built-in classes such as Error, Array and Map. The most useful case in testing is a custom error that carries extra context. Module 9 covers error handling in depth.

📄 extend-builtins.js

class ApiError extends Error {
  constructor(message, { status, url } = {}) {
    super(message);              // sets message and the stack trace
    this.name = "ApiError";
    this.status = status;
    this.url = url;
  }
}

function checkResponse(res) {
  if (res.status >= 400) {
    throw new ApiError(`Request failed with ${res.status}`, res);
  }
  return res;
}

try {
  checkResponse({ status: 503, url: "/api/orders" });
} catch (e) {
  console.log(e instanceof ApiError, e instanceof Error);
  console.log(`${e.name}: ${e.message} (${e.url})`);
}

class TagList extends Array {
  hasTag(tag) { return this.includes(tag); }
}
const tags = TagList.from(["smoke", "p1"]);
console.log(tags.hasTag("p1"), tags.filter((t) => t !== "p1") instanceof TagList);

⌨️ Terminal

node extend-builtins.js

🖥️ Output

true true
ApiError: Request failed with 503 (/api/orders)
true true

Array methods such as filter return instances of the subclass, so the result still has hasTag.


Advertisement

🧱 Abstract-Style Base Classes

JavaScript has no abstract keyword, but you can enforce the same rules: prevent creating the base class directly with new.target, and throw if a child forgets to implement a required method:

📄 abstract.js

class Shape {
  constructor() {
    if (new.target === Shape) throw new TypeError("Shape is abstract; create a subclass");
  }
  area() {
    throw new Error(`${this.constructor.name} must implement area()`);
  }
  describe() {
    return `${this.constructor.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(r) { super(); this.r = r; }
  area() { return Math.PI * this.r ** 2; }
}
class Square extends Shape {
  constructor(side) { super(); this.side = side; }   // forgot area()
}

console.log(new Circle(2).describe());
for (const attempt of [() => new Shape(), () => new Square(3).describe()]) {
  try { attempt(); } catch (e) { console.log(e.message); }
}

⌨️ Terminal

node abstract.js

🖥️ Output

Circle with area 12.57
Shape is abstract; create a subclass
Square must implement area()

🧩 Composition vs Inheritance

Inheritance models an “is a” relationship (a Tester is an Employee). Composition models a “has a” relationship: an object holds other objects and uses them. Deep inheritance trees become rigid; composition keeps pieces small and reusable.

📄 composition.js

// Composition: a page HAS a header and a cart widget
class Header {
  constructor(page) { this.page = page; }
  search(term) { return `${this.page}: search "${term}"`; }
}
class CartWidget {
  constructor(page) { this.page = page; }
  count() { return `${this.page}: read cart count`; }
}

class ProductPage {
  constructor() {
    this.header = new Header("ProductPage");
    this.cart = new CartWidget("ProductPage");
  }
}

const product = new ProductPage();
console.log(product.header.search("laptop"));
console.log(product.cart.count());

⌨️ Terminal

node composition.js

🖥️ Output

ProductPage: search "laptop"
ProductPage: read cart count

💡 Tip: A common, healthy design for test frameworks: one shallow BasePage for truly shared behaviour (open, wait, title), and components (header, footer, modal, table) composed into pages. Avoid chains like BasePage → AuthenticatedPage → AdminPage → AdminUsersPage.


🧪 Tester Scenario: A BasePage and Two Page Objects

📄 pages.js

class FakePage {
  log = [];
  goto(url) { this.log.push(`goto ${url}`); }
  fill(sel, v) { this.log.push(`fill ${sel}=${v}`); }
  click(sel) { this.log.push(`click ${sel}`); }
}

class BasePage {
  path = "/";
  constructor(page, baseURL = "https://qa.example.com") {
    this.page = page;
    this.baseURL = baseURL;
  }
  open() {
    this.page.goto(this.baseURL + this.path);
    return this;
  }
  logout() {
    this.page.click("#logout");
  }
}

class LoginPage extends BasePage {
  path = "/login";
  login(user, pass) {
    this.page.fill("#email", user);
    this.page.fill("#password", "***");
    this.page.click("button[type=submit]");
    return this;
  }
}

class CartPage extends BasePage {
  path = "/cart";
  open() {                         // extend the shared behaviour
    super.open();
    this.page.click("#accept-cookies");
    return this;
  }
  checkout() {
    this.page.click("#checkout");
  }
}

const page = new FakePage();
new LoginPage(page).open().login("asha@sqatools.in", "Secret@1");
new CartPage(page).open().checkout();
new CartPage(page).logout();          // inherited from BasePage
console.log(page.log.join("\n"));

⌨️ Terminal

node pages.js

🖥️ Output

goto https://qa.example.com/login
fill #email=asha@sqatools.in
fill #password=***
click button[type=submit]
goto https://qa.example.com/cart
click #accept-cookies
click #checkout
click #logout

Each page object declares only what is different: its path and its own actions. CartPage overrides open but reuses the base version with super.open().


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Create a class Vehicle with wheels and a method info(), and a subclass Bike that sets wheels to 2. Print new Bike().info().

Show answer

📄 practice1.js

class Vehicle {
  constructor(wheels) { this.wheels = wheels; }
  info() { return `${this.constructor.name} with ${this.wheels} wheels`; }
}
class Bike extends Vehicle {
  constructor() { super(2); }
}
console.log(new Bike().info());

🖥️ Output

Bike with 2 wheels

Q2. Override toString() in a subclass Admin of User so it adds " (admin)" to the parent result, using super.

Show answer

📄 practice2.js

class User {
  constructor(name) { this.name = name; }
  toString() { return `User ${this.name}`; }
}
class Admin extends User {
  toString() { return `${super.toString()} (admin)`; }
}
console.log(String(new User("Ravi")), "|", String(new Admin("Asha")));

🖥️ Output

User Ravi | User Asha (admin)

Q3. Write class ValidationError extends Error with a field property, throw it for an empty email, and print the name, message and field.

Show answer

📄 practice3.js

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}
try {
  const email = "";
  if (!email) throw new ValidationError("email", "Email is required");
} catch (e) {
  console.log(e.name, "|", e.message, "|", e.field, "|", e instanceof Error);
}

🖥️ Output

ValidationError | Email is required | email | true

Q4. Predict the output, then run it.

class A {
  who() { return "A"; }
  hello() { return `hello from ${this.who()}`; }
}
class B extends A {
  who() { return "B"; }
}
console.log(new A().hello(), "|", new B().hello());
Show answer

📄 practice4.js

class A {
  who() { return "A"; }
  hello() { return `hello from ${this.who()}`; }
}
class B extends A {
  who() { return "B"; }
}
console.log(new A().hello(), "|", new B().hello());

🖥️ Output

hello from A | hello from B

hello is inherited, but this.who() is looked up on the actual object, so a B instance uses B‘s who.

Q5. Give Animal a static method create(...args) that returns new this(...args), and show that Cat.create("Tom") returns a Cat.

Show answer

📄 practice5.js

class Animal {
  constructor(name) { this.name = name; }
  static create(...args) { return new this(...args); }
}
class Cat extends Animal {}
const tom = Cat.create("Tom");
console.log(tom instanceof Cat, tom.constructor.name, tom.name);

🖥️ Output

true Cat Tom

Q6. Rewrite this inheritance as composition: class Car extends Engine is wrong because a car is not an engine. Make Car have an engine and delegate start() to it.

Show answer

📄 practice6.js

class Engine {
  start() { return "engine started"; }
}
class Car {
  constructor() { this.engine = new Engine(); }
  start() { return `car: ${this.engine.start()}`; }
}
console.log(new Car().start());

🖥️ Output

car: engine started

🧠 MCQ Quiz: Inheritance

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which keyword creates a subclass?
  2. What must a child constructor do before using this?
  3. How do you call the parent version of an overridden method?
  4. If a child class has no constructor, what happens?
  5. Is new Dog() instanceof Animal true when Dog extends Animal?
  6. Are static methods inherited by subclasses?
  7. What does new.target help you do?
  8. When you extend Error, what should the constructor call first?
  9. Which describes composition?
  10. In a parent method, which version of this.helper() runs for a child instance?

💼 Interview Questions and Answers

Q1. How does inheritance work in JavaScript classes?

class Child extends Parent links Child.prototype to Parent.prototype (for instance methods) and Child to Parent (for static members). A child constructor must call super(...) before using this. Methods can be overridden, and super.method() calls the parent implementation. Under the hood it is prototype-based inheritance.

Q2. What is the difference between overriding and overloading?

Overriding is redefining a parent method with the same name in a child class, which JavaScript supports. Overloading is defining several methods with the same name but different parameter lists, which JavaScript does not support: a later definition simply replaces the earlier one. Instead, use default parameters, rest parameters or an options object and check the arguments inside one method.

Q3. When should you prefer composition over inheritance?

When the relationship is “has a” rather than “is a”, when behaviour must be mixed and matched (a page may or may not have a search bar, a cart widget or a modal), or when a hierarchy is getting deeper than two levels. Composition keeps classes small and independent, and avoids fragile base classes where one change breaks many children. Use shallow inheritance for genuinely shared core behaviour.

Q4. Why does a custom error class call super(message) and set this.name?

📄 timeout-error.js

class TimeoutError extends Error {
  constructor(ms) {
    super(`Timed out after ${ms} ms`);
    this.name = "TimeoutError";
  }
}
const e = new TimeoutError(5000);
console.log(e.name, "-", e.message, "-", e.stack.split("\n")[0]);

⌨️ Terminal

node timeout-error.js

🖥️ Output

TimeoutError - Timed out after 5000 ms - TimeoutError: Timed out after 5000 ms

super(message) lets Error set message and capture the stack trace. Setting name makes the error type appear in logs and stack traces, and lets code distinguish errors by instanceof or name.


Advertisement

❓ Frequently Asked Questions

🤔 Does JavaScript support multiple inheritance?

No. A class can extend only one class. Use composition or mixins (functions that add methods to a class) to combine behaviour from several sources.

🤔 Can I extend a class from a library or a built-in?

Yes. You can extend built-ins like Error, Array, Map and EventEmitter, and classes exported by libraries.

🤔 What is the difference between super() and super.method()?

super(...) calls the parent constructor and is only allowed in a child constructor. super.method() calls a parent method and can be used in any method of the child.

🤔 How deep should a class hierarchy be?

Usually one or two levels. Deeper hierarchies are hard to understand and change; prefer composition instead.


🏁 Summary

  • class Child extends Parent inherits instance methods, fields and static members.
  • A child constructor must call super(...) before using this.
  • Override methods by redefining them, and extend them with super.method().
  • Extend built-ins such as Error for custom errors; use new.target for abstract-style base classes.
  • Prefer shallow hierarchies and composition (“has a”) over deep inheritance trees.

Next, continue with Lesson 41: Getters, Setters, Private Fields.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in