nico-c
10/20/2016 - 6:33 PM

Inheriting from EventEmitter using extends keyword and constructor() object

Inheriting from EventEmitter using extends keyword and constructor() object

// in a greetr.js file // 
////////////////////////

'use strict';

var EventEmitter = require('events');

// module.exports exports the class like any variable or function
// keyword extends removes the need for the Greetr function contructor
// and the need for util. inherits and the need for util = require('util')
module.exports = class Greetr extends EventEmitter {
    // constructor() is like building a function constructor
	constructor() {
        // to directly call the parent of the constructor: super();
        // you have to say what yr inherting from so need to extends
		super();
		this.greeting = 'Hello world!';
	}
	
	greet(data) {
	  // this is a template literal so use backtick: `
		console.log(`${ this.greeting }: ${ data }`);
		this.emit('greet', data);
	}
}


////////////////
// IN APP.JS //
//////////////
// we'll need to import the class variable from the other file
var Greetr = require('./greetr');