8. function Ork() {
this.description = "I am an Ork"
}
!
Ork.prototype.describe = function() {
console.log(this.description)
}
!
var ork = new Ork()
ork.describe() // I am an Ork
!
setTimeout(ork.describe, 100) // undefined
setTimeout(ork.describe.bind(ork), 100) // I am an Ork
17. “The observer pattern is a software design pattern in
which an object, called the subject, maintains a list of
its dependents, called observers, and notifies them
automatically of any state changes, usually by calling
one of their methods.” — Wikipedia
19. Observer
function OrkMaster(name) {
this.name = name
}
!
OrkMaster.prototype.notify = function(ork, message) {
console.log(this.name + " here " +
ork.name + " told me he "
+ message)
}
!
OrkMaster.prototype.observe = function(ork) {
ork.registerObserver(this)
}
20. Putting it all together
var master = new OrkMaster("Uruk-hai")
var gobgrub = new Ork("Gobgrub")
var nazsnaga = new Ork("Nazsnaga")
!
master.observe(gobgrub)
master.observe(nazsnaga)
!
gobgrub.smash("human")
nazsnaga.smash("drawf")
!
// Uruk-hai here Gobgrub told me he smashed human
// Uruk-hai here Nazsnaga told me he smashed drawf