###Javascript Patterns ..thx @ Sorella
####Composition
function compose() {
var traits = [].slice.call(arguments)
return traits.reduce(function(result, trait) {
for (var k in trait)
if (k in result) throw new Error("Duplicated property: " + k)
else result[k] = trait[k]
return result
}, {})
}
var CanBreath = {
breath: function() {
return "*" + this.name + " breathes*\n"
}
}
var CanSpeak = {
speak: function(what) {
return '"' + what + '," says ' + this.name + "\n"
}
}
var Alice = compose(CanBreath, CanSpeak, { name: "Alice" })
var WhiteRabbit = compose(CanBreath, CanSpeak, { name: "the White Rabbit" })
var Dinah = compose(CanBreath, { name: "Dinah" })
console.log(
Dinah.breath(),
WhiteRabbit.speak("Oh my fur and whiskers! I am late, I am late!"),
Alice.speak("A rabbit with a clock! How curious!")
)
####Inheritance
var Being = {
inherit: function(characteristics) {
var newBeing = Object.create(this)
for (var k in characteristics) newBeing[k] = characteristics[k]
return newBeing
}
}
var Animal = Being.inherit({
breath: function() {
return "*" + this.name + " breathes*\n"
}
})
var Human = Animal.inherit({
speak: function(what) {
return '"' + what + '," says ' + this.name + "\n"
}
})
var Anthropomorphised = Animal.inherit({
speak: function(what) {
return '"' + what + '," says ' + this.name + "\n"
}
})
var Alice = Human.inherit({
name: 'Alice'
})
var WhiteRabbit = Anthropomorphised.inherit({
name: 'the White Rabbit'
})
var Dinah = Animal.inherit({
name: "Dinah"
})
console.log(
Dinah.breath(),
WhiteRabbit.speak("Oh my fur and whiskers! I am late, I am late!"),
Alice.speak("A rabbit with a clock! How curious!")
)
#####Contact
irc.freenode.net ##javascript