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.
I cannot reproduce your problem. Here is my setup:
parent.js
child.js
main.js
And running
main.js:The source code is clonable via Git at the following Gist: https://gist.github.com/4704412
Aside: to clarify the
exportsvsmodule.exportsdiscussion: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 usemodule.exports. For example: