Javascript域模型对象的约定 [英] Convention for Javascript Domain Model Objects

查看:70
本文介绍了Javascript域模型对象的约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我必须在C#中创建域模型对象,我可能会这样做:

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

在Javascript中,定义这些对象的惯例是什么?我在想这样的事情:

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


推荐答案

是的,基本上可以看到。唯一要补充的是你应该原型方法。你如何将原型设计为设计,我通常更喜欢在内部对类进行此操作,但标记为只在需要时运行,并且只运行一次。

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.

这篇关于Javascript域模型对象的约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆