Skip to content

Instantly share code, notes, and snippets.

@benspaulding
Created July 28, 2021 19:19
Show Gist options
  • Save benspaulding/e36f413f8742149d51d4fea8c63a5732 to your computer and use it in GitHub Desktop.
Save benspaulding/e36f413f8742149d51d4fea8c63a5732 to your computer and use it in GitHub Desktop.
Prototypical vs Classical "inheritance" in JavaScript

Prototypical vs Classical "inheritance" in JavaScript

Prototypical

function Rotorcraft(rotorBlades) {
  this.rotorBlades = rotorBlades;
}
Rotorcraft.prototype = {
  start() {
    console.log(this, 'Brrrrrrrr...');
  },
};

function Helicopter(rotorBlades, mainRotors = 1) {
  Rotorcraft.call(this, rotorBlades);
  this.mainRotors = mainRotors;
}
Helicopter.prototype = {
  __proto__: Rotorcraft.prototype,
  autoRotate() {
    console.log(this, 'Eeeek!');
  },
};

const helo = new Helicopter(3);

function Autogyro(rotorBlades, rearProp = true) {
  Rotorcraft.call(this, rotorBlades);
  this.rearProp = rearProp;
}
Autogyro.prototype = {
  __proto__: Rotorcraft.prototype,
  jumpTakeOff() {
    console.log(this, 'Wheeee!');
  },
};

const gyro = new Autogyro(2);

Classical

class Rotorcraft {
  constructor(rotorBlades) {
    this.rotorBlades = rotorBlades;
  }
  start() {
    console.log(this, 'Brrrrrrrr...');
  }
}

class Helicopter extends Rotorcraft {
  constructor(rotorBlades, mainRotors = 1) {
    super(rotorBlades);
    this.mainRotors;
  }
  autoRotate() {
    console.log(this, 'Eeeek!');
  }
}

const helo = new Helicopter(3);

class Autogyro extends Rotorcraft {
  constructor(rotorBlades, rearProp = true) {
    super(rotorBlades);
    this.rearProp;
  }
  jumpTakeOff() {
    console.log(this, 'Wheeee!');
  }
}

const gyro = new Autogyro(2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment