Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Require class with initializers

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??

like image 396
Will03uk Avatar asked Apr 16 '11 22:04

Will03uk


2 Answers

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.

like image 159
ThiefMaster Avatar answered Oct 18 '22 20:10

ThiefMaster


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')
like image 44
Will03uk Avatar answered Oct 18 '22 20:10

Will03uk