Util.inherits (constructor, Superconstructor) is a function that implements prototype inheritance between objects. The object-oriented nature of JavaScript is prototype-based and differs from common class-based ones. JavaScript does not provide the language-level attributes of object inheritance, but is implemented through prototype replication, which we discuss in Appendix A, where we will only describe the usage of util.inherits, as shown here:
var util = require (' util '); function Base () { this.name = ' base '; This.base = 1991; This.sayhello = function () { console.log (' Hello ' + this.name);} ;} Base.prototype.showName = function () { console.log (this.name);}; function Sub () { this.name = ' Sub ';} Util.inherits (Sub, Base), var objbase = new Base (); Objbase.showname (); Objbase.sayhello (); Console.log (objbase); var Objsub = new Sub (); Objsub.showname ();//objsub.sayhello (); Console.log (objsub);
Code laycode-v1.1
We have defined a base object base and a sub,base inherited from base with three properties defined within the constructor and a function defined in a prototype, inherited through the util.inherits implementation. The results of the operation are as follows:
Basehello base{Name: ' base ', base:1991, SayHello: [Function]}sub{name: ' Sub '}
Note that the sub inherits only the functions defined by base in the prototype, and neither the base property created inside the constructor nor the SayHello function are inherited by Sub. Also, properties defined in the prototype are not output by Console.log as an object's property. If we remove Objsub.sayhello (); This line of comments, you will see:
Node.js:201throw e; Process.nexttick error, or ' Error ' event on first Tick^typeerror:object # have no method ' SayHello ' at Object.
(/home/byvoid/utilinherits.js:29:8) at Module._compile (module.js:441:26) at Object. JS (module.js:459:10) at Module.load (module.js:348:31) at Function._load (Module.js:308:12) at array.0 (module.js : 479:10) at Eventemitter._tickcallback (node.js:192:40)
Node. js's prototype inheritance function util.inherits