Creating a class in NodeJS

How to 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 message

TypeError: the object is not a function in Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)

What do I need to fix?

+5
source share
2 answers

I managed to get it working 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 am not sure that creating one is reserved, but I found that I do not need it.

+3
source

:

module.exports.create = function() {
  return new mySuperClass();
}
module.exports._class = mySuperClass;

:

module.exports = mySuperClass;

require module.export. , , , .

{ create: function () { ... }, _class: function (ar) { ... } } ( module.exports ) . , .

( , ), _i.

+1

All Articles