
//Handler
function Rescuer(code, next) {
this._code = code;
this._next = next;
//HandleRequest()
this.help = function(code) {
if (this._code === code) {
this.toHelp();
} else if (next != undefined) {
next.help(code);
}
}
}
//ConcreteHandler
function Firefighter(next) {
Rescuer.apply(this, [1, next]);
this.toHelp = function() {
console.log("call firefighters");
}
}
//ConcreteHandler
function Police(next) {
Rescuer.apply(this, [2, next]);
this.toHelp = function () {
console.log("call the police");
}
}
//ConcreteHandler
function Ambulance(next) {
Rescuer.apply(this, [3, next]);
this.toHelp = function () {
console.log("call an ambulance");
}
}
var ambulance = new Ambulance();
var police = new Police(ambulance);
var firefighter = new Firefighter(police);
firefighter.help(1);
//printed: call firefighters
firefighter.help(2);
//printed: call the police
firefighter.help(3);
//printed: call an ambulance