Reputation: 63
How can I create an array of my class?
I see it something like this:
in main.js
....
mySuperClass = require('./mySuperClass.js');
objArray = new Object();
...
objArray["10"] = new mySuperClass(10);
console.log(objArray["10"].getI);
objArray["20"] = new mySuperClass(20);
console.log(objArray["20"].getI);
objArray["30"] = new mySuperClass(30);
console.log(objArray["30"].getI);
in mySuperClass.js
var _i = 0;
var mySuperClass = function(ar) {
_i = ar;
}
mySuperClass.prototype.getI = function()
{
return _i
}
module.exports.create = function() {
return new mySuperClass();
}
module.exports._class = mySuperClass;
After exec, I get an error
TypeError: object is not a function at Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)
What I need to correct?
Upvotes: 6
Views: 13581
Reputation: 6198
Change these lines:
module.exports.create = function() {
return new mySuperClass();
}
module.exports._class = mySuperClass;
to this:
module.exports = mySuperClass;
The require function returns the value of the module's module.export
. If you set this value to the constructor of your class, it will return that constructor which you can use like in your usage example.
Currently you're trying to call an object that's something like { create: function () { ... }, _class: function (ar) { ... } }
(the value of module.exports
in your function) as a constructor. This object is not a function, so the error message tells you so.
However, this solution alone will not make your class function as expected (if I understand correctly what your class is supposed to do), because the class instances share the global variable _i
.
Upvotes: 1
Reputation: 13621
I was able to get it to work by using the following:
var _i = 0;
var mySuperClass = function(ar) {
_i = ar;
}
mySuperClass.prototype.getI = function()
{
return _i
}
/*module.exports.create = function() {
return new mySuperClass();
} */
module.exports.mySuperClass = mySuperClass;
module = require('./myclass.js');
objArray = new Object();
objArray["10"] = new module.mySuperClass(10);
console.log(objArray["10"].getI());
objArray["20"] = new module.mySuperClass(20);
console.log(objArray["20"].getI());
objArray["30"] = new module.mySuperClass(30);
console.log(objArray["30"].getI());
Based on what I read here: http://nodeguide.com/beginner.html#the-module-system, you add properties to the export object, and use them as such. I'm not sure if the create one is reserved, but I found that I didn't need it.
Upvotes: 3