🏛️ Object-Oriented Programming

Constructor Chaining

Project Evidence Required
Use super() to chain constructors and forward initialization data.
Assessment Method
Code review: super(data, gameEnv) calls

What it is

A subclass constructor must call super(...) before it can use this. The super() call invokes the parent class’s constructor, letting the parent do its initialization first. Arguments passed to super() are forwarded up the chain.

Why it matters

Without super() the parent never initializes — the child would start life half-built, missing whatever the parent normally sets up (position, sprite handle, engine binding). JavaScript actually throws a ReferenceError if you try to access this in a subclass constructor before calling super().

How GateGame implements it

GameLevelMazeSub calls super(gameEnv) immediately so the base GameLevel can register the level with the engine and bind the canvas context. Each entity subclass (Player, Npc, SplineBarrier) does the same with super(data, gameEnv) — the base class handles all the universal entity setup (position, sprite loading, hit box), the subclass adds its own fields after.

Code Example

class GameLevelMazeSub extends GameLevel {
  constructor(gameEnv) {
    super(gameEnv);            // ← required first call
    this.classes = [ /* ... */ ];
  }
}

Key Takeaway

super() is non-optional in subclasses — and the right place to forward initialization data so the parent can do its job.