Node.js examples for Object:Class in ES6
using VanillaJS syntax (prototypes) vs ES6 Syntax for class definition
// //from ww w. ja v a 2s . co m function EventEmitter() { this._callbacks = {}; EventEmitter.prototype._initializeEvent = function (eventName) { if (typeof this._callbacks[eventName] == 'undefined') { this._callbacks[eventName] = []; } } EventEmitter.prototype.on = function (eventName, callback) { this._initializeEvent(eventName); this._callbacks[eventName].push(callback); } EventEmitter.prototype.emit = function (eventName, data) { this._initializeEvent(eventName); for (let i = 0; i < this._callbacks[eventName].length; i++) { this._callbacks[eventName][i](data); } } } // using ES6 syntax (classes) class EventEmitterES6 { constructor() { this._callbacks = {} } _initializeEvent(eventName) { if (typeof this._callbacks[eventName] == 'undefined') { this._callbacks[eventName] = []; } } on(eventName, callback) { this._initializeEvent(eventName); this._callbacks[eventName].push(callback); } emit(eventName, data) { this._initializeEvent(eventName); this._callbacks[eventName].map(x => x(data)); } } let emitter = new EventEmitter(); emitter.on('print', console.log); emitter.on('print', (x) => console.log(x + " " + x)); emitter.emit('print', 'Hello world'); let emitterES6 = new EventEmitterES6(); emitterES6.on('print', console.log); emitterES6.emit('print', 'Hello world from ES6');