Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Straightforward Way to Extend Class in Node.js

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(){
} 
like image 759
Sara Fuerst Avatar asked Apr 19 '16 18:04

Sara Fuerst


People also ask

How do I extend a class in node JS?

By default, each class in Node. js can extend only a single class. That means, to inherit from multiple classes, you'd need to create a hierarchy of classes that extend each other. If you're with NPM v4 or lower, just append a -S to the install command to automatically add it to the dependencies in package.

How do you extend classes in JavaScript?

The extends keyword is used to create a child class of another class (parent). The child class inherits all the methods from another class. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.

Can a function extend a class in JavaScript?

The extends keyword can be used to subclass custom classes as well as built-in objects. Any constructor that can be called with new (which means it must have the prototype property) can be the candidate for the parent class. The prototype of the ParentClass must be an Object or null .


1 Answers

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
like image 70
Nick Messing Avatar answered Nov 09 '22 17:11

Nick Messing