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
  • 2
    You need to understand how Node modules work. In particular, globals aren't really global. nodejs.org/api/modules.html Commented Dec 25, 2013 at 0:12

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Is export a module or is it default in node.js?
@RobinVandenBroeck exports is a special object in each module which is visible outside of the module (and no other object is visible outside).

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.