BlackMamba
BlackMamba

Reputation: 10254

Why the added prototype method should be added after `util.inherits`?

I want to know why the added prototype method should be added after util.inherits?

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

function Server() {
    console.log('init');
}

Server.prototype.say = function(){
    console.log('say');
}

util.inherits(Server, EventEmitter);

var server = new Server();
server.on('abc', function(){
    console.log('abc');
})

server.emit('abc');
server.say();

There is an error when i run this code:

C:\Users\elqstux\Desktop\wy.js:19
server.say();
       ^
TypeError: undefined is not a function
    at Object.<anonymous> (C:\Users\elqstux\Desktop\wy.js:19:8)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

But if i modified code to this:

util.inherits(Server, EventEmitter);

Server.prototype.say = function(){
    console.log('say');
}

the code runs ok.

Upvotes: 0

Views: 127

Answers (1)

Rafał Łużyński
Rafał Łużyński

Reputation: 7312

From the node.js documentation https://nodejs.org/docs/latest/api/util.html#util_util_inherits_constructor_superconstructor:

util.inherits(constructor, superConstructor)

Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.

So basically after you use util.inherits on Server, its prototype is replaced by new, inheriting from EventEmitter, hence previously added methods are lost.

Upvotes: 1

Related Questions