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


i want know why added prototype method should 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 error when run code:

c:\users\elqstux\desktop\wy.js:19 server.say();        ^ typeerror: undefined not function     @ object.<anonymous> (c:\users\elqstux\desktop\wy.js:19:8)     @ module._compile (module.js:460:26)     @ object.module._extensions..js (module.js:478:10)     @ module.load (module.js:355:32)     @ function.module._load (module.js:310:12)     @ function.module.runmain (module.js:501:10)     @ startup (node.js:129:16)     @ node.js:814:3 

but if modified code this:

util.inherits(server, eventemitter);  server.prototype.say = function(){     console.log('say'); } 

the code runs ok.

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

util.inherits(constructor, superconstructor)

inherit prototype methods 1 constructor another. the prototype of constructor set new object created superconstructor.

so after use util.inherits on server, prototype replaced new, inheriting eventemitter, hence added methods lost.


Comments

Popular posts from this blog

javascript - three.js lot of meshes optimization -

smartface.io - Proper way to change color scheme for whole application -

Email notification in google apps script -