javascriptnode.jsdata-objects

Data Model Definition Standard in JavaScript/Node


I recently started programming in JavaScript (Server side) and Node.js. I come from Java background where there is a concrete standard on how you define Data Object, which is Java Bean. Do we have any such standards in JavaScript/Node on how we define Data Objects (similar to Java Beans)?

I have researched at many places and couldn't find any standards. I have seen following styles but not sure which is better or recommended:

//bean1.js
module.exports = function() {
var obj = {};
obj.name = '';
obj.department = '';

return obj;

}

//bean2.js
module.exports = function() {

this.name = '';
this.department = '';

return this;

}

//bean3.js
module.exports = function(param) {
var obj = {};

if(param === undefined) {
return obj;
}

obj.name = param.name;
obj.department = param.department;

return obj;

}

//bean4.js
module.exports = {
    name : '';
    department : '';
}

Solution

  • So based on some more studies, research and answers from some of the folks from Node/JavaScript community, I think I have better clarity on how to create data objects and differences between the above 4 styles (see code snippet in above question) of creating objects.

    Based on answers, JavaScript doesn't have any standard on creating data objects (as compared to Java Bean Specification). It's more of a free style and depends upon the use case of what kind of object you need to create, i.e. Singleton or more dynamic objects (multiple new instances).

    So if you need a simple object without ceating new instances of that object then beanjs.4 is the best example to create data object. This is simple but the limitation is that the object created is Singleton and you can't create new instances from this object definiton.

    //bean4.js
    module.exports = {
        name : '';
        department : '';
    }
    

    If your use case is to create multiple new instances then use a function which can return a object. In the question above, bean1.js, bean2.js and bean3.js are all doing the same thing and either one could be used to create new objects. Using functions to return objects is known as "Generators" or "Factories" or "Psedo-Constructor".

    Here is an example on using function to return objects (Factory Pattern):

    function Person(firstName, lastName) {
        var person = {};
    
        person.firstName = firstName;
        person.lastName = lastName;
    
        return person;
    
    }
    
    var person = new Person('foo', 'bar'); //create object from Person
    

    To read detailed discussion on this question, visit this link: https://groups.google.com/forum/#!topic/nodejs/Drezeitaxbc