PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] How to extend class inside module.exports in node js?

 August 24, 2022     class, extends, module, module.exports, node.js     No comments   

Issue

So, using Node.js v18.3, I don't want to write new class every time in there:

module.exports = {Class1, Class2, /*etc...*/};

That's why I using this way of doing it:

module.exports = {
  ClassName: class ClassName {
    constructor(...args) {
      // properties...
    };
  },
};

But, when I try to extend the class:

module.exports = {
  ClassName: class ClassName {
    constructor(...args) {
      // properties...
    };
  },

  AnotherClass: class AnotherClass extends ClassName {
    // it does not work, sadly...
  },
};

It gives this error:

  AnotherClass: class AnotherClass extends ClassName {
                                           ^

ReferenceError: ClassName is not defined

Tried to work around it with this.ClassName:

  AnotherClass: class AnotherClass extends this.ClassName {
    // does not work too...
  },

But it did not work either:

  AnotherClass: class AnotherClass extends this.ClassName {
                                                ^

TypeError: Class extends value undefined is not a constructor or null

First of all, why does it? Why does it not work in first time, without this.?
Second, how do I fix this or is there any other way doing this, without manually putting all classes in object, as I showed at the beginning of the question?


Solution

You’re doing a class expression rather than a class declaration, so at the time your code runs inside module.exports the classes are not defined yet, so cannot be extended from.

Instead of using a single module.exports you could use multiple exports, for example:

exports.Class1 = class Class1 {
  /* … */
};

exports.Class2 = class Class2 extends exports.Class1 {
  /* … */
};


Answered By - davecardwell
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing