Straightforward Way to Extend Class in Node.js

19,442

It depends how you defined your first class, I suggest using something like this:

class SomeClass {
}

module.exports = SomeClass

then in your extend:

const SomeClass = require('./dir/file.js')

class MyNewClass extends SomeClass {
}

module.exports = MyNewClass
Share:
19,442
Sara Fuerst
Author by

Sara Fuerst

I am the Founder and Lead Developer of Tibsar Software LLC. I have always had a passion for software development. Today I use this passion to help aspiring business owners build their software based business. I focus on creating quality software products that can scale with their business and meet their unique needs.

Updated on June 13, 2022

Comments

  • Sara Fuerst
    Sara Fuerst almost 2 years

    I am moving a plain Javascript class into Node.js. In the plain Javascript I use:

    class BlockMosaicStreamer extends MosaicStreamer{
    }
    

    I can't seem to find a simple way to implement this in Node.js. In my node project in BlockMosaicStreamer.js I have:

    'use strict'; 
    function BlockMosaicStreamer(){
    } 
    

    How would I extend MosaicStreamer which is in ./MosaicStreamer.js?

    'use strict'; 
    function MosaicStreamer(){
    } 
    
  • Sara Fuerst
    Sara Fuerst about 8 years
    However, my classes are defined as shown in the question. Using class in node causes a lot of issues
  • Bergi
    Bergi about 8 years
    @tibsar: Then use a transpiler. There should be nothing that stops you from using ES6 today.
  • Nick Messing
    Nick Messing about 8 years
    @tibsar, you can update node.js, I'm using 5.9.1 and it works just fine.
  • Sara Fuerst
    Sara Fuerst about 8 years
    Is there absolutely no way to do it the way I'm doing it?
  • Nick Messing
    Nick Messing about 8 years
    @tibsar, it will take way more time then writing in es6 and transpiling or updating node
  • Sara Fuerst
    Sara Fuerst about 8 years
    @NickMessing Can you show me how you would do it this way?
  • Nick Messing
    Nick Messing about 8 years
    @tibsar, take a look at typescriptlang.org/play choose Classes Example and take a look at JavaScript result.