2

I'm currently learning how to use node.js (And OOP javascript with prototypes) but I've a little problem. I'll give you the code:

foo.js:

var foo = function(){};
foo.prototype.a = function(){
    return 'foo';
};

bar.js:

var bar = new Foo();
console.log(bar.a);

app.js

require('./foo.js');
require('./bar.js');

Instead of working I get a ReferenceError telling me that foo is not defined. Can somebody tell me how I should do this?

1

1 Answer 1

2

First, proper export:

foo.js

var foo = function(){};
foo.prototype.a = function(){
    return 'foo';
};

exports.ref_to_foo = foo;

and then proper import:

bar.js

var foo_module = require('./foo.js');
var Foo = foo_module.ref_to_foo;

var bar = new Foo();
console.log(bar.a);
2
  • Is export a module or is it default in node.js? Dec 25, 2013 at 0:18
  • 1
    @RobinVandenBroeck exports is a special object in each module which is visible outside of the module (and no other object is visible outside).
    – freakish
    Dec 25, 2013 at 0:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.