How to inherit methods from one prototype to another using the Node.js usel module?

Asked

Viewed 284 times

3

I was watching the video of a guy explaining events of Node.js and at the end he makes a small module using util.inherit to inherit from one prototype constructor to another. Although I know the syntax of call and have caught a sense of the method util.inherit in API DOCS, I couldn’t capture the semantics of the code in general.

Module builder

var EventEmitter - require('events').EventEmitter;
var inherits = require('util').inherits;

function FireDetector(){
    EventEmitter.call(this);
}

inherits(FireDetector, EventEmitter);

FireDetector.prototype.smoke = function(amount){
    if(amount > 0.5) {
        this.emit('fire').
    }
}

module.exports = FireDetector;

Example of module usage (only as bonus)

var FireDetector = require('./firedetector');

fireDetector = new FireDetector();

fireDetector.on('fire', function() {
    console.log('fire fire fire');
});

1 answer

3


Perhaps your doubt will be clarified if you take a look at Node/usel code on Github.

At the bottom is a shortcut to import/inherit from an existing prototype.
The source code is:

exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

That is to say:

FireDetector.super_ = EventEmitter
FireDetector.prototype = Object.create(EventEmitter.prototype, {
    constructor: {
      value: FireDetector,
      enumerable: false,
      writable: true,
      configurable: true
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.