SivaDotRender
SivaDotRender

Reputation: 1651

exporting objects in node.js modules

I have a node 'class' defined in a separate file as follows:

function Node_class(){
 //code
}

Node_class.prototype = {

    function _1 : function(){
      //code
    }

};

module.exports.Node_class= Node_class;

now when I want to create a new instance of Node_class in a separate file so I did the following:

var node_object = new require('./node_class').Node_class();
node_object.function_1();//is not defined

node_object.function_1() is not defined in the separate file for some reason. Can someone help me export this node 'class' properly?

Upvotes: 1

Views: 31

Answers (1)

Mike S
Mike S

Reputation: 42355

There are a couple of things that are causing this. First, there's a space where there shouldn't be here:

function _1 : function(){

It's probably just a typo, but it should be:

function_1 : function(){

Second, if you're going to call new on require('./node_class').Node_class you need to wrap it in parenthesis:

var node_object = new (require('./node_class').Node_class)();

Or, alternatively, you could do:

var Node_class = require('./node_class').Node_class;
var node_object = new Node_class();

Upvotes: 1

Related Questions