Nodejs Requires a 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 tried

 var Person = require('modulename').Person('Will'); 

but it just gave unidentified. How do I require a class with initializers in nodejs ??

+7
source share
2 answers
 var mod = require('modulename'); var somePerson = new mod.Person('Will'); 

In code, you call the constructor directly without new , so this bound to the global context, and not to the new Person object. And since you did not return this to your function, you received an undefined error.

See a short demo at http://jsfiddle.net/ThiefMaster/UCvC2/ .

+14
source

The found fix, although a bit inconvenient, I wanted the import on one line to be imported, and only one instance of it looked bad. I think this was not interpreted as a function. @ThiefMaster thanks for the "new", I also forgot about it: /

 var will = new (require('modulename').Person)('Will') 
+1
source

All Articles