composition

over

 

inheritance

object

 

 

 

class

 

ES6

We now have 'class'.

But do we want to use it?

 

Inheritance

Vehicle

Land Vehicle

Car

Ferrari

Composition

Engine

Ferrari

Tire

Mirror

Break

Seat

But inheritance

works pretty well

in your example!

OK, but

what happens if...

Vehicle

Land Vehicle

Engine

Amphicar

Tire

Mirror

Break

Seat

skrew propeller

rudder

Other problems w.

class inheritance

  • fragile base class

  • diamond problem

So how can I use

composition in Javascript?

With pure Javascript

 

Oh wait, there's a lib

for that...

 

but it sucks.

(by Eric Elliott)

What's a stamp?

[A] composable factory function [...] that returns object instances[...].

https://github.com/stampit-org/stamp-specification

Installation

$ npm install stampit

Let's build a stamp

var stampit = require('stampit');

var myStamp = 
        stampit()

                .props() 

                .refs()

                .init()

                .methods()

                .static()


        stampit()

                .refs()

               .props()

.init()

.methods()

.static()

Add instance safe,

deeply merged properties to 

the objects created from the stamp


        stampit()

                .refs()

               .props()

.init()

.methods()

.static()

Add properties which are passed 

by reference to the objects

created from the stamp


        stampit()

                .refs()

               .props()

.init()

.methods()

.static()

Add private data

and privileged methods to 

the objects created from the stamp


        stampit()

                .refs()

               .props()

.init()

.methods()

.static()

Add public methods to 

the objects created from the stamp


        stampit()

                .refs()

               .props()

.init()

.methods()

.static()

Add methods to the stamp, 

but not to the objects

created from the stamp

DEMO

Additional facts

  • also available for react
    https://github.com/stampit-org/react-stamp
     

  • can convert javascript constructor functions
    with convertConstructor()
     

  • created as example for the book
    'Programming Javascript Applications'
    (see http://bit.ly/pjsa-free-ebook)

I wanna tinker too

http://bit.ly/ES6BP

WISHIN' YA

GR8 FUN

composition-over-inheritance

By Marc Dix

composition-over-inheritance

  • 6,514