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??
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??
Share Improve this question edited Oct 25, 2015 at 17:25 Sam Hosseini 7572 gold badges9 silver badges18 bronze badges asked Apr 16, 2011 at 22:46 Will03ukWill03uk 3,4448 gold badges36 silver badges40 bronze badges2 Answers
Reset to default 14var 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/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')