adamloving / js-extend-demo

Simplifying Javascript prototypal inheritance with extend

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simple Javascript Inheritance

Problem

Make class inheritance in Javascript as easy as CoffeeScript.

class A
  @name = 'apple'

class B extends A
  constructor:
    super()
    @data = 'mydata'

To do the same thing in JS requires...

function A() {
  this.name = 'apple';
}; // constructor function

function B() { 
  A.call(this);
  this.data = 'banana';
}

B.prototype = new A();

It's hard to get the hang of. The instance assigned into B.prototype becomes the object to be copied into new instances of B. Using A.call(this) in the constructor is funky. Same with B.prototype.method.call(this) to call super class methods.

I had two Aha! moments understanding prototype based inheritance:

  1. Only functions (AKA constructors) have prototypes. Instances don't have them.
  2. function X() {} always runs before var X = function(); (duh, right?)

Requirements for simplifying syntax

  • Simpler syntax for B.prototype = new A();
  • Avoid (preferably with a super method):
    • A.call(this) // call super constructor
    • A.prototype.method.call(this) // call super's method
  • Copy class data and methods (on class, not instance)
  • Preserve instanceof operator

Alternatives

  • CoffeeScript __extends - not quite librifiable since generates code
  • node's util.inherits - doesn't copy data, just functions
  • lodash _.create - half of the puzzle still requires knowledge of prototype
  • John Resig's Class.extend - Winner!
    • I added a couple lines to copy class data + methods on to the derived class (inspired by CoffeeScript __extend)

About

Simplifying Javascript prototypal inheritance with extend


Languages

Language:JavaScript 100.0%