CalvinR
CalvinR

Reputation: 744

How do I properly create prototype objects from another file in Node.js?

I'm running into a really frustrating problem in Node.js.

I'll start with what I'm doing.

I'm creating an object in a file and then exporting the constructor and creating it in other files.

My objects are defined like so:

File 1:

var Parent = function() {};

Parent.prototype = {
     C: function () { ... }
}

module.exports = Parent;

File 2:

var Parent = require('foo.js'),
      util = require('util'),
      Obj = function(){ this.bar = 'bar' };
util.inherits(Obj, Parent);
Obj.prototype.A = function(){ ... };
Obj.prototype.B = function(){ ... };
module.exports = Obj;

I'm trying to use the object like so in another file

File 3:

var Obj = require('../obj.js'),
      obj = new Obj();

obj.A(); 

I receive the error:

TypeError: Object [object Object] has no method 'A'

however when I run Object.getPrototypeOf(obj) I get:

{ A: [Function], B: [Function] }

I have no idea what I'm doing wrong here, any help would be appreciated.

Upvotes: 2

Views: 4372

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159125

I cannot reproduce your problem. Here is my setup:

parent.js

var Parent = function() {};

Parent.prototype = {
  C: function() {
    console.log('Parent#C');
  }
};

module.exports = Parent;

child.js

var Parent = require('./parent'),
    util = require('util');

var Child = function() {
  this.child = 'child';
};

util.inherits(Child, Parent);

Child.prototype.A = function() {
  console.log('Child#A');
};

module.exports = Child;

main.js

var Child = require('./child');
child = new Child();

child.A();
child.C();

And running main.js:

$ node main.js
Child#A
Parent#C

The source code is clonable via Git at the following Gist: https://gist.github.com/4704412


Aside: to clarify the exports vs module.exports discussion:

If you want to attach new properties to the exports object, you can use exports. If you want to completely reassign exports to a new value, you muse use module.exports. For example:

// correct
exports.myFunc = function() { ... };
// also correct
module.exports.myFunc = function() { ... };

// not correct
exports = function() { ... };
// correct
module.exports = function() { ... };

Upvotes: 5

Related Questions