Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including subclassjs with all npm packages installed. Try it out:

var subclassjs = require("subclassjs")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

subclassjs v1.3.0

Yet another inheritance utility

subclassjs v1.3.0

Easy simple class inheritance tool, just works perfect in es5.

For those who don't like to use "compilers" but like to use class.

  • Class definition by a function:zap:, not by an object.
  • instanceof works.
  • Sets prototype.constructor properly
  • parent method call support
  • no global side effect

Usage

Basic

subclass = require('subclassjs');

// define a class
var Child = subclass(Parent, function (pt) {

    pt.constuctor = function () { /* blah */ };

    pt.myMethod = function () { /* ... */ };

    //...

});

The first argument pt of the defining function is the prototype object of the child class to be defined. You can define methods of the child class by setting the properties on it.

Default parent

You can omit first argument. If it's omitted, it inherits Object class.

var MyClass = subclass(function (pt) { /* ... */ });

The above is the same as the below;

var MyClass = subclass(Object, function (pt) { /* ... */ });

Inheritance

You can inherit classes. The second parameter of the defining function is parent's prototype (not the parent class itself) and you can call parent's method through it.


var ChildClass = subclass(ParentClass, function (pt, parent) {

    pt.constructor = function () {

        parent.constructor.apply(this, arguments);

        // do something

    };

    pt.myMethod = function () {

         var result = parent.myMethod.apply(this, arguments);

         // do something

         return result;

    };

});

Static methods

You can define static methods.


var ChildClass = subclass(ParentClass, function (pt) {

    pt.constructor.staticMethod = function (str) {

        // ...

    };

});

In this case, you can call ChildClass.staticMethod()

Other approaches to write classes

  • [runtime]
    • Ext JS ( Ext.extend )
    • function-branch
    • npm search of inheritance, subclass or subtype gives you a lot of examples
  • [through compiler]
    • babel
    • TypeScript
    • CoffeeScript
    • Traceur
    • sweetjs
    • etc...
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free