Victorino
Victorino

Reputation: 1641

Exports whole object with functions

i tried found answer in stackoverflow and can't find any answer about this i just started learning NodeJS . and i got a question, is there any way how can i exports whole object with his functions or i can exports only functions of object?

thanks for advice!

when i try it i got error like this

TypeError: object is not a function

i got simple code like this :

animal.js

var Animal = {

   name : null,

   setName : function(name) {

      this.name = name;

   },

   getName : function() {

       console.log("name of animal is " + this.name);
   }

}


exports.Animal = Animal;

and server.js

  var animal = require('./animal');

  var ani = new animal.Animal();

Upvotes: 0

Views: 31

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123493

The error is because new expects a Function while Animal is a plain Object.

Though, with the Object, you could use Object.create() to create instances:

// ...

var ani = Object.create(animal.Animal);

Otherwise, you'll have to define Animal as a constructor Function:

function Animal() {
    this.name = null;

    // ...
}

exports.Animal = Animal;

Note: Depending on precisely what you want to accomplish, Functions are a type of Object and can hold additional properties.

function Animal(name) {
    this.name = name || Animal.defaultName;
}

Animal.defaultName = null;

Upvotes: 2

Related Questions