Decorator Design Pattern (Prototypes and context)
JS
S
JavaScriptDecorator Design Pattern (add behaviors to an existing object without changing it). .on() is only available on the events object, so a search through the prototype chain happens. .on() is called via the prototype chain (on the events object). 'this.handlers' is only available on the events object, so a search through the prototype chain happens
1// Original Object
2// ------------------------------------
3const coreEvents = {
4 on(event, handler){
5 // Won't check prototype chain as *hasOwnProperty()* targets only current context
6 if(!this.hasOwnProperty('handlers')){
7 this.handlers = [];
8 }
9
10 this.handlers.push({
11 event: event,
12 handler: handler
13 });
14 }
15}
16
17coreEvents.on('dispatch:master', ()=>{});
18console.log(coreEvents);
19// CoreEvents has 'dispatch:master'
20
21// Decorated Object
22// ------------------------------------
23const decoratedEvents = Object.create(coreEvents);
24decoratedEvents.on('dispatch:slave', ()=>{});
25console.log(decoratedEvents);
26// decoratedEvents has 'dispatch:slave'Created on 8/31/2017