On Jan 10, 2015, at 5:04 AM, Prabhash Rathore <[email protected]> wrote:
> 
> Based on your replies, I think this is the best way to represent a data 
> object as it's just data and object can represent this data:
> module.exports = {
> 
>     name 
> : '';
> 
>     department 
> : '';
> }
> However I have noticed people using function() to create data objects and 
> then they just return an object inside the function (see below example)? Is 
> there any specific use case or reason on using function instead of using just 
> object literal?



It depends on what it is you want your module to offer. Say the module provides 
a bunch of utility functions. Then you may just choose to export each function 
and be done:

str_utils.js:

exports.uncamelcase   = function(str) { …. };
exports.is_palindrome = function(str) { …. };
exports.is_numeric    = function(str) { …. };

Then someone can use it thus:

var str_utils = require(‘str_utils’);

if( str_utils.is_palindrome(person_name) === true )
    console.log(“Well, aren’t you special!”);

On the other hand, if your module returns a constructor/class to be used for 
instantiating new objects, then you may wish to do this:

module.exports = Car;

function Car(name, cost, mpg, alternative)
{
    this.name = name;
    this.cost = cost;
    this.env_damage = mpg;
    this.alternative = alternative;
}

Car.prototype.appeal =
function()
{
    return(this.cost/this.mpg);
};

Car.prototype.snark =
function()
{
    return(this.alternative.advise());
};

Then someone could:

var Car = require(‘car’);
var metro = require(‘metro’);

var new_car = new Car(‘Hummer’, 80000, 2, metro);

if( new_car.appeal() > 700 )
    console.log(“Congratulations on your fancy”, new_car.name, “but”, 
new_car.snark());

Etc. Keep in mind the part played by require/module caching (if you return an 
object, it will be cached and returned from the cache at the next require — 
this may or may not be what you want: I use it as a way to load dependencies 
without passing them around).

        —ravi


-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/6CC0F73D-A104-487B-83F6-0930105B236C%40g8o.net.
For more options, visit https://groups.google.com/d/optout.

Reply via email to