I am learning Node.js recently. I have a question about the function util.inherits in Node.js. Can I use extends in coffeescript to replace it? If not, what are the differences between them?
I am learning Node.js recently. I have a question about the function util.inherits in
Share
Yes, you can use
extendsin place of it.As for the differences? Let’s start with a look at CoffeeScript:
Let’s look at the JavaScript the CoffeeScript compiler produces for this JavaScript:
So,
__extendsis used to declare the inheritence relationship betweenBandA.Let’s restate
__extendsa bit more readably, in CoffeeScript:(You can check that this is a faithful reproduction by compiling it back to JavaScript.)
Here’s what’s happening:
parentare set onchild.ctoris created, with its instances’constructorproperties set to the child, and itsprototypeset to the parent.prototypeis set to an instance ofctor.ctor‘sconstructorwill be set tochild, andctor‘s prototype itself isparent.__super__property is set toparent‘sprototype, for use by CoffeeScript’ssuperkeyword.node’s documentation describes
util.inheritsas follows:In conclusion, you don’t need to use
util.inheritsif you’re using CoffeeScript’s classes; just use the tools CS gives you, and you get bonuses like thesuperkeyword.