Convention for Javascript Domain Model Objects

可紊 提交于 2019-12-21 19:57:36

问题


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;
}

回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/546624/convention-for-javascript-domain-model-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!