jozenbasin jozenbasin - 4 years ago 184
Javascript Question

Node js extending inherited object (as enum)

It doesn't seem like you can extend a class object (in this case used as an enum) in Node.js. Example

Foo

class Foo {}
Foo.action = {};
Foo.action.jump = 1;
module.exports = Foo;


Bar

var Foo = require('./foo');
var Baz = require('./baz');

class Bar extends Foo {
constructor(){
super();
this.baz = new Baz();
}
}

Bar.action.stay = 2;
module.exports = Bar;


Usage (edit, it's used in a class)

var Bar = require('./bar');
class Baz {
constructor(){
console.log(Bar.action); //undefined
}
}
module.exports = Baz;


I believe this is a cyclical dependency issue.

Answer Source

I believe this is a cyclical dependency issue.

Yes, the cyclical dependency between Bar and Baz, using assignment to the Common.js module.exports, makes Bar an empty object in the Baz.js module. The solution is to use module properties only. (Btw, this would've worked fine in declarative ES6 modules).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download