Last active
February 9, 2020 20:24
-
-
Save matthewstokeley/f4d54b8cb347279ab963a5e1fed336ac to your computer and use it in GitHub Desktop.
composition and javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// composition and javascript | |
// @todo review | |
// composition is often contrasted with inheritance as a mechanism for allowing different components, | |
// modules or classes to communicate. both inheritance and composition are considered highly coupled - | |
// composition is less coupled than inheritance. | |
// object-oriented composition with dependency injection | |
class Book { | |
constructor (Page: PageClass) { | |
// this book class is now composed with an | |
// injected Page class that is implementing a PageClass interface | |
this.page = new Page({}) | |
} | |
} | |
// composition with objects implementing the revealing module design pattern | |
const book = (function(page) { | |
return { | |
// this method is an alias for the object method or instantiated class that we've composed the book module with | |
method: page.getNumber() | |
} | |
})() | |
// compositions with objects implementing the revealing module | |
const book = (function(page, ink) { | |
return { | |
method: page.getNumber() + ink.spill() | |
} | |
})() | |
// composition with functional javascript via closures | |
let compose = function(composition) { | |
return function(object) { | |
return object[composition.getName()].method | |
} | |
} | |
// compositions with functional javascript via closures | |
// (proof of concept) | |
let composer = function(fn1) { | |
return function(fn2) { | |
return fn2 | |
} | |
} | |
const walk = composer(function(obj) { | |
for (let key of obj) { | |
console.log(obj[key]) | |
} | |
}) | |
let log = walk(function(obj) { fn1(obj) }) | |
log({key: 'value'}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment