selfish
Class-free, pure prototypal multiple inheritance that lets you write expressive, well-structured code.
Install
server-side
npm install selfish
client-side
bower install selfish
Require
server-side
var Base = Base
client-side RequireJS
Examples
Basics
// Instead of creating classes, you create prototype objects. Let's look// at this simple example first:var Dog = Base // Forget about classes, javascript is a prototypal language:typeof Dog // object // Use the new operator to create an instance:var dog = dog // 'Ruff! Ruff!' // Alternatively you can use the legacy new() function but keep in mind that// the new operator is faster in most browsersvar dog = Dogdog // 'Ruff! Ruff!' // Forget about special `instanceof` operator, use JS native method instead:Dogprototype // true // Objects inherit from objects, what could be more object oriented than// that ?var Pet = Dog // All arguments passed to the constructor are forwarded to the `initialize`// method of instance. var pet = 'Labrador' 'Benzy'pet // 'Labrador Benzy'pet // ''pet // 'Ruff! Ruff!'
Object composition
// In some programs recombining reusable pieces of code is a better option: var HEX = Base var RGB = Base var CMYK = Base // Composing `Color` prototype out of reusable components:var Color = Base var pink = Color// RGBpink // 255pink // 192pink // 203 // CMYKpink // 0.2471pink // 0.2039pink // 0.0000
Combining composition & inheritance
var Pixel = Color var pixel = 11 23 'CC3399'pixel // 11:23@#CC3399Pixelprototype // true // Pixel instances inhertis from `Color`Colorprototype // true // In fact `Pixel.prototype` itself inherits from `Color.prototype`, remember just simple and// pure prototypal inheritance where objects inherit from objects.Colorprototype // true
TODO
This is a list of things I may introduce in newer versions.
- Add
testling
badge - Add examples about private variables (closures)
- Add guidelines on how to use the lib for common cases
- Add
requirejs
test - Better merge? in-depth merge (like lodash). Two different
extend
methods ? - Do a full prototype chaining ?
var Extra = Base;var instance = ;Baseprototype; // true :DExtraprototype; // true :DFooprototype; // false :(Barprototype; // false :(
- Clone inner objects:
var someBase = outer: inner: 1 var Extra = Base;var e = ;eouterinner = 3;someBaseouterinner === 1; // should be true