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.

Revisions

  1. benspaulding created this gist Jul 28, 2021.
    77 changes: 77 additions & 0 deletions js-paradigms.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,77 @@
    # Prototypical vs Classical "inheritance" in JavaScript

    ## Prototypical

    ```js
    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

    ```js
    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);
    ```