For example I have the following class
var Person = function(name)
{
this.sayHi = function()
{
return "Hello, " + name + "!";
}
}
exports.Person = Person;
In nodejs I have tried
var Person = require('modulename').Person('Will');
but this just gave unidentified. How do I require a class with initializers in nodejs??
var mod = require('modulename');
var somePerson = new mod.Person('Will');
In you code you called the constructor directly without new
, so this
was bound to the global context instead of a new Person
object. And since you did not return this
in your function you got the undefined error.
See http://jsfiddle.net/ThiefMaster/UCvC2/ for a little demo.
Found the fix, although slightly awcward looking, I wanted the import on one line as import the class only too create one instance of it looked bad. I guess it wasn't being interpreted as a function. @ThiefMaster thanks about 'new', I forgot about that as well :/
var will = new (require('modulename').Person)('Will')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With