Skip to content

dtcyganok/subtype

Repository files navigation

subtype

Simple OOP library, which can be useful for the environment ≤ ES5. Works fast like native inheritance (see benchmarks).

Install

For npm users:

npm install subtypejs

For bower users:

bower install subtype

Usage

In a browser:

<script src="path/to/subtype.js"></script>

In an AMD loader:

define(['subtype'], function (Subtype) {

  // code...

});

In node.js:

var Subtype = require('subtypejs');

// code...

And then:

var Human = Subtype.extend({
  constructor: function (name) {
    this.name = name;
  },
  say: function (words) {
    return this.name + ': ' + words;
  }
});

var Actor = Human.extend({
  say: function (words) {
    // explicit call the super method
    return 'actor ' + Human.prototype.say.call(this, words);
  }
});

var human = new Human('Robert');
console.log(human.say('Hi!')); // => "Robert: Hi!"

var actor = new Actor('Jeremy');
console.log(actor.say('Hello!')); // => "actor Jeremy: Hello!"

console.log(
  human instanceof Human &&
  human instanceof Subtype &&
  actor instanceof Actor &&
  actor instanceof Human &&
  actor instanceof Subtype
); // => true

console.log(
  Subtype === Subtype.prototype.constructor &&
  Human === Human.prototype.constructor &&
  Actor === Actor.prototype.constructor
); // => true