Robin Van den Broeck
Robin Van den Broeck

Reputation: 1678

Using prototypes in other files using node.js

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?

Upvotes: 2

Views: 1303

Answers (1)

freakish
freakish

Reputation: 56547

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

Upvotes: 2

Related Questions