Thursday, March 31, 2011

Convention for Javascript Domain Model Objects

Hi all,

If I have to create a domain model object in C# I might do something like this:

public class Person
{
    Public string Name { get; set; }
    Public string Gender { get; set; }
    Public int Age { get; set; }
}

In Javascript, what is the convention for defining such objects? I'm thinking something like this:

NAMESPACE.Person = function() {
    this.name = "";
    this.gender = "";
    this.age = 0;
}
From stackoverflow
  • I don't think there is much of a "convention" but you can declare "private" variables and Crockford shows you how to here

    
    function Constructor(...) { var that =
    this; var membername = value; function
    membername(...) {...}
    
    }
    

    Note: The function statement

    
    function membername(...) {...}
    

    is shorthand for

    
    var membername = function
    membername(...) {...};
    

    To round out the answer, you would do this, you'll notice I do it a little differently

    
    // class
    function Person()
    {
        // private variable
        var name = "Default Value";
    
        // getter
        this.getName = function()
        {
         return name;
        }
    
        // setter
        this.setName = function(s)
        {
         name = s;
        }
    }
    
    
    // instanciate an object
    var p = new Person();
    
    // alerts: Default Value
    alert(p.getName());
    
    p.setName("def");
    
    // alerts: def
    alert(p.getName());
    
    // alerts: undefined
    alert(p.name);
    
  • Yeah, spot on basically. The only thing to add is that you should prototype methods on. How you proto can be situational to the design, I generally prefer to do this internally to the class, but flagged so it only runs when required, and only the once.

    NAMESPACE.Person = function() {
        this.name = "";
        this.gender = "";
        this.age = 0;
    
        if(!NAMESPACE.Person._prototyped)
        {
            NAMESPACE.Person.prototype.MethodA = function () {};
            NAMESPACE.Person.prototype.MethodB = function () {};
            NAMESPACE.Person.prototype.MethodC = function () {};
    
            NAMESPACE.Person._prototyped = true; 
        }
    }
    

    Explaining why: The reason for this is performance and inheritance. Prototyped properties are directly associated with the class (function) object rather than the instance, so they are traversable from the function reference alone. And because they are on the class, only a single object needs to exist, not one per instance.

    Allen : would it be NAMESPACE.Person._prototyped, or NAMESPACE.Person.prototype._prototyped

0 comments:

Post a Comment