Reputation: 34687
I have node.js app in which I have a class.js
module in which
var MyClass = module.exports.MyClass = function MyClass(){}
Object.defineProperty(MyClass, 'MyArray', ['value1','value2']);
MyClass.prototype.MyFunction = function(){
//---
}
Then I require
it in my main app.js
var MyClass = require('./class.js');
var myInstance = new MyClass(); // TypeError: object is not a function
but it throws that error when I try to instantiate it with new
. What am I doing wrong here? I've tried a lot of alterations but none works, but I do know that it(or something close to it) used to work..
Upvotes: 0
Views: 929
Reputation: 151561
var MyClass = require('./class.js').MyClass;
You have to assign to MyClass
the MyClass
member which you set on the exports
object. Otherwise you are invoking new
with the module instance returned by require
.
Otherwise you could export like this:
var MyClass = module.exports = exports = function MyClass(){}
and keep your require
statement as is. In this case you are exporting one and only one function from your module. (Technically, you don't need to assign to exports
in the line above. However, if you don't then exports
ceases to be an alias of module.exports
. I prefer to keep them in sync.)
Upvotes: 2