1

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.

jozenbasin
  • 2,142
  • 2
  • 14
  • 22
  • 1
    It's [working fine for me](https://jsfiddle.net/xbtngykb/). There's something weird going on here. – 4castle Feb 05 '17 at 00:53
  • Your code works in my local machine too. which nodejs version You use? – num8er Feb 05 '17 at 00:57
  • @4castle `var b = new Bar(); console.log(b.action)` – guest271314 Feb 05 '17 at 01:04
  • 2
    @guest271314 That's going to be `undefined`, because there's a difference between `Bar.action` and `Bar.prototype.action`. This question is about just the inheritance of the "static" members. – 4castle Feb 05 '17 at 01:05
  • @guest271314 user is trying to: `extend a class object` I think question is not correct – num8er Feb 05 '17 at 01:06
  • @jozenbasin, have You tried to require them like this: `require('./foo')`, `require('./bar')` - because in my local machine I'm getting exception when I don't define correct path, maybe that is the solution to Your issue. But overall everything works as expected in nodejs env (v.7.4.0) – num8er Feb 05 '17 at 01:10
  • I added that the call is within class. – jozenbasin Feb 05 '17 at 01:55
  • Being inside a class won't change the output. Please create a [mcve], so that we can reproduce the problem. – 4castle Feb 05 '17 at 04:34
  • OK I replicated the issue to the smallest case possible. I think the issue is cyclical referencing. I guess I am screwed. – jozenbasin Feb 05 '17 at 16:17
  • The only problem I can see with writing to `Bar.action.jump` is [that it thereby sets `Foo.action.jump` as well](https://stackoverflow.com/questions/10131052/crockfords-prototypal-inheritance-issues-with-nested-objects/), being the *same* object. – Bergi Feb 05 '17 at 17:04

1 Answers1

1

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).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375