Wheels Class
Simple and powerful classical inheritance for JavaScript. Super lightweight, with no dependencies and fully compatible with CommonJS / npm, AMD and standard browser script tag include.
Install
wheels-class
can be installed with CommonJS / npm, AMD or standard browser script tag:
npm
npm install wheels-class
AMD / RequireJS
;
Traditional browser script tag
Usage
Class definition
Pass an object to the constructor to create a class and add the object's properties to the class prototype
property:
var Foo = { return "Hello :)"; }; var foo = ;foo; // => "Hello :)"
Alternatively, you can pass a function to the constructor, and it will be executed in the scope of the class. That means that, whithin the function, this
is the class itself. Also, the function will receive the prototype
property of the class as the first argument:
var Foo = { // `this` is the class, here Foo this { return "I am a class method"; } // first argument is the class `prototype` property (here Foo.prototype) proto { return "Hello :)"; } }; var foo = ; Foo; // => "I am a class method"foo; // => "Hello :)"
Class inheritance
The subclass
method creates a subclass and accepts the same arguments as the constructor:
var Animal = { return "Yum :)"; }; var Cat = Animal; var nyan = ;nyan; // => "Yum :)"nyan; // => "Meow!" // The subclass also stores a reference to the superclassCat_superclass === Animal // => true // And the instance stores a reference to the parent prototypenyan_parent === Animalprototype // => true
Include, augment and reopen
The include
method accepts one or more objects and copies their properties to the class' prototype
property:
var Duck = ; Duck; var donald = ;donald; // => "Quack!"
The augment
method accepts one or more objects and copies their properties to the class:
var Foo = ; Foo; Foo; // => "I am a class method!"
The reopen
method accepts the same arguments as the Class
constructor: if you pass an object, its properties get added to the class prototype, if you pass a function it is executed in the scope of the class, passing the prototype as the first argument.
var Human = john = ; // Passing an objectHuman; john; // => "Goo goo goo joob!" // Passing a functionHuman; Human; // => "ergo sum."john; // => "Yum!"