用于编写javascript对象的最干净的格式 [英] Cleanest format for writing javascript objects

查看:88
本文介绍了用于编写javascript对象的最干净的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写javascript对象的最简洁格式是什么?

What is the cleanest format for writing javascript objects?

目前我用以下格式编写我的文件

Currently I write mine in the following format

if (Namespace1 == null) var Namespace1 = {};
if (Namespace1.NameSpace2 == null) Namespace1.NameSpace2 = {};

Namespace1.NameSpace2.Class1 = function(param1,param2){
     // define private instance variables and their getters and setters
     var privateParam = param1;
     this.getPrivateParam = function() {return privateParam;}
     this.publicParam1 = param2;
}

Namespace1.Namespace2.Class1.prototype = {
     publicParam1:null,
     publicFunction1:function() {/* Function body*/}
}

这种格式现在运行良好,因为YUI文档软件能够解析它,并且评论和回馈良好的文件。但它没有提供的是在命名空间中声明静态全局方法的简洁方法。我也想知道是否有更简洁的方法来声明私有变量。

That format works well right now, as the YUI documentation software is able to parse it, and the comments and give back good documentation. But what it doesn't provide is a clean way to declare static global methods within the namespace. I am also wondering if there is a cleaner way to declar private variables as well.

我的问题是,有没有人有一个更清晰的方法来定义javascript对象比这个,如果是这样,为什么你的方法更好?

My question is, is anyone out there have a cleaner way of defining javascript objects than this, and if so, why is your method better?

谢谢!

推荐答案

模块模式可以帮助你:

 var Namespace1 = Namespace1 || {};
    Namespace1.Namespace2 = Namespace1.Namespace2 || {};

    Namespace1.Namespace2.Class1 = function(param1, param2) {
        // define private instance variables and their getters and setters
        var privateParam = param1;
        this.getPrivateParam = function() { return privateParam; }
        this.publicParam1 = param2;

        return {
            init: function() {
                alert('hi from Class1');
            }
        }
    } ();

您可以在此处阅读更多相关信息: http://yuiblog.com/blog/2007/06/12/module-pattern/

You can read more about it here: http://yuiblog.com/blog/2007/06/12/module-pattern/

    Namespace1.Namespace2.Class1.init();

这篇关于用于编写javascript对象的最干净的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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