0

Given two modules a and b. I know that it is possible to expose a's functionality to another module using the module.exports. I probably do not use it correctly.

a.js

function A() { ... }
A.prototype.func = function() { ... }

function test() {
    new A().func();
}

test();
module.exports = {
    A : new A()
};

The test() is working correctly. But the following breaks:

b.js

var A = require("./a");
A.func(); //throws an exception

How do I export the whole A module with its functionality?

Update: executing console.log(A) over b (as a second line), does not reveal any of A's methods and variables.

1
  • As per your edit, if you want to see the keys on A, try Object.keys(A). Commented Nov 26, 2012 at 8:13

1 Answer 1

1

Try this:

module.exports = new A();

You won't be able to instantiate a new A in b, but it seems like that's what you want.

Edit:

Or you could change b.js to:

var A = require('./a');
A.A.func();

But this is likely not what you want.

The idea is that whatever exports is will be what is returned from require. It's exactly the same reference.

Sign up to request clarification or add additional context in comments.

3 Comments

You exported an object with a property called A set to the instance.
firstly thank you. secondly, do you have any clue why i cannot access A.obj within module b when i have set in module a the following: A.obj = { key : "value"};?
Yes. obj is attached to the function A, not the instance returned via new A(). Using new creates an object from its prototype and calls the constructor, nothing more. If you want access to things attached to the function A, you'll have to return that and instantiate it in b.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.