Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active December 2, 2020 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpivo/028001b7fac3eacd03d1265bf0bbc6fa to your computer and use it in GitHub Desktop.
Save rpivo/028001b7fac3eacd03d1265bf0bbc6fa to your computer and use it in GitHub Desktop.
Inheritance: Classes vs Functions

Inheritance: Classes vs Functions

The code snippet at the end of this gist shows a three-way inheritance scenario for both classes and functions.

Function example: A inherits from B, which inherits from C
Class example: D inherits from E, which inherits from F

Function A and class D should each have all inherited properties from their respective inheritance chains.

The function example below requires roughly 70% less characters than the class example.

This leaves out a lot of the syntactic sugar you can get from using classes, like working with getters and setters. I also think classes make it easier to see the inheritance occurring.

Still, using function inheritance has its merits and should be considered in most scenarios.

// Inheritance with Functions

function A() {
  B.call(this)
  this.foo = 'foo'
}

function B() {
  C.call(this)
  this.bar = 'bar'
}

function C() {
  this.baz = 'baz'
}

const instanceOfA = new A()

console.log({ instanceOfA })
// { instanceOfA: A { baz: 'baz', bar: 'bar', foo: 'foo' } }

/* * * * * * * * * * * * * * * * */

// Inheritance with Classes

class D {
  constructor() {
    this.foo = 'foo'
  }
}

class E extends D {
  constructor() {
    super()
    this.bar = 'bar'
  }
}

class F extends E {
  constructor() {
    super()
    this.bas = 'baz'
  }
}

const instanceOfF = new F()

console.log({ instanceOfF })
// { instanceOfF: F { foo: 'foo', bar: 'bar', bas: 'baz' } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment