Search code examples
javascriptclasssuperjavascript-inheritance

how to manage super() constructor parameters in javascript


This is a short piece of code from mazeContainer.js with only necessary part-

import Cell from "./cell.js";
import Player from "./player.js";

export default class Maze {
  ....
  setup(){
    for (let rowNum = 0; rowNum < this.rows; rowNum++) {
            let row = [];

            for (let colNum = 0; colNum < this.columns; colNum++) {
                let cell = new Cell(this.ctx, rowNum, colNum, this.cellWidth, this.cellHeight);
                row.push(cell);
            }
            this.grid.push(row);
  }
  
  drawMap(){
    ....
    let player = new Player(this.goal, this.lastRow, this.lastColumn);
    ....
  }
}

And player.js-

import Cell from "./cell.js";

export default 
class Player extends Cell {
    constructor(goal, lastRow, lastColumn) {
        super();                                    // need to manage this statement
        this.goal = goal;
        this.lastRow = lastRow;
        this.lastColumn = lastColumn;
    }
    ....
}

Now here's what I'm having trouble with.

I've just encountered the super keyword and what I've got to know so far is that I need to call super method before using this. That's not an issue. But here I also need to provide all parameters for Cell's constructor.

As you can see, the Cell class has got many parameters in its constructor, so how do I hand them over to new Player(....)?

Is there a better way to achieve this?


Solution

  • • The extends keyword makes the methods of the animal class available inside the cat class.
    • The constructor, called when you create a new Cat object, accepts two arguments, name and usesLitter.
    • The super keyword calls the constructor of the parent class. In this case, super(name) passes the name argument of the Cat class to the constructor of the Animal class. When the Animal constructor runs, it sets this._name = name; for new Cat instances.
    • _usesLitter is a new property that is unique to the Cat class, so we set it in the Cat constructor.

    class Animal {                            
      constructor(name) {           
        this._name = name;
      }
      get name() {
        return this._name;
      }
    } 
    
    
    class Cat extends Animal {           
      constructor(name, usesLitter) {
        super(name);                    // The super keyword calls the constructor of the parent class.
        this._usesLitter = usesLitter;
      }
        get usesLitter() {
        return this._usesLitter;
      }
    }
    
    
    const bryceCat = new Cat('Bryce', true);
    console.log(bryceCat.name);               //Output: Bryce
    console.log(bryceCat.usesLitter);       //Output: true