0

In Node.js (ver. 0.12.0 ) I have a class with method defined like this:

In ./constructor.js:

function Pow() {}
Pow.prototype.wow = require("./wow/definition.js");

module.exports = Pow;

In ./wow/definition.js:

var Pow = require("../constructor.js");

function wow() {

  return new Pow();
}

module.exports = wow;

In ./index.js:

var Pow = require("./constructor.js");
var pow = new Pow();
pow.wow();

The last line of ./index.js throws the following error:

object is not a function
    at Pow.wow(./wow/definition.js:5:10)

Running the same code in Google Chrome (ver. 45.0.2454.101 64-bit ), which also uses the V8 engine but not the CommonJS require system, does not result in an error:

function Pow() {}
Pow.prototype.wow = wow;

function wow() {

  return new Pow();
}

var pow = new Pow();
pow.wow();

Can anyone tell me why, in Nodejs, require("./constructor.js") returns a constructor in ./index.js but a non-constructable object in ./wow/definition.js?

StudentsTea
  • 329
  • 4
  • 16
  • 1
    don't use circular dependencies! – Daniel A. White Oct 09 '15 at 01:47
  • @DanielA.White - Unless you're implementing a clone method – StudentsTea Oct 09 '15 at 01:48
  • nope, just don't use circular dependencies. – bhspencer Oct 09 '15 at 01:55
  • You're all so smart; tell me *why* it's bad. Seriously, [witchcraft](http://stackoverflow.com/questions/16024940/how-do-i-clone-a-javascript-class-instance)? Is that your argument? Or is there something more substantive than the usual JavaScript lore? – StudentsTea Oct 09 '15 at 02:04
  • 1
    Circular dependencies are not supported by commonjs (or at least the support is somewhat buggy). So don't use it. – slebetman Oct 09 '15 at 03:26
  • @slebetman Thank you! I've submitted your comment as the answer below. Please feel free to submit one yourself, if you'd like. I'll mark it as correct and upvote it. – StudentsTea Oct 09 '15 at 04:02
  • As it turns out, voodoo and screaming aren't an acceptable answer. ;) – StudentsTea Oct 09 '15 at 04:06
  • @user1739757: After googling a bit I found that circular dependency support was added somewhere around 0.14 in order to support the streams module. So it's supported but with caveats - exported properties remain undefined until the require completes. So you need some sort of `init()` method to link the properties of each module to each other later. – slebetman Oct 09 '15 at 06:34

1 Answers1

0

As @slebetman mentions in his comment on the original question, support for circular dependencies in CommonJS, the specification most similar to the implementation of require() in NodeJs, is still somewhat buggy. So, avoid ciricular dependencies until support for them in NodeJs has been worked out.

StudentsTea
  • 329
  • 4
  • 16