“最佳实践”;“全球”;JavaScript中的变量?

“最佳实践”;“全球”;JavaScript中的变量?,javascript,Javascript,我将所有代码放在NS中,类似于jQuery的结构。我有几个全局到NS的变量,我想把它们括起来,然后像这样进行访问->global.variable\u name 下面是我做这件事的方式。这是好的做法吗?如果我不必调用var Global=new GlobalMaker() 我使用所有大写字母表示全局常量 var NS = ( function ( window, undefined ) { /* all my code is here */ } )( ) /** (including this

我将所有代码放在NS中,类似于jQuery的结构。我有几个全局到NS的变量,我想把它们括起来,然后像这样进行访问->
global.variable\u name

下面是我做这件事的方式。这是好的做法吗?如果我不必调用
var Global=new GlobalMaker()

我使用所有大写字母表示全局常量

var NS = ( function ( window, undefined ) { /* all my code is here */ } )( )

/** (including this code)
 *GlobalMaker
 */

var GlobalMaker = function()
{
    this.tag_array = [];
    this.current_tag;
    this.validate_input_on;
    this.JSON_ON = 1;                              // selector between JSON and LON
    this.GATEWAY = 'class.ControlEntry.php';       // for Ajax calls
    this.PICTURES = '../pictures/';                // for composing tweets
    this.PASS = 0;
    this.FAIL = 1;
    this.NOTDEFINED = 2;
};
var Global = new GlobalMaker();

/**
 *Global 
 */

var Global = 
{
    tag_array:          [],
    current_tag:        0,
    validate_input_on:  0,
    JSON_ON:            1,                             
    GATEWAY:            'class.ControlEntry.php',       
    PICTURES:           '../pictures/',                
    PASS:               0,
    FAIL:               1,
    NOTDEFINED:         2
}

这在不使用构造函数的情况下执行等效操作:

var Global = {
    tag_array: [],
    // current_tag, // huh?
    // validate_input_on, // huh?
    JSON_ON: 1,
    GATEWAY: 'class.ControlEntry.php',
    PICTURES: '../pictures/',
    PASS: 0,
    FAIL: 1,
    NOTDEFINED: 2
};
但我不理解后两个没有初始化的声明


但是,请注意,如果按照上面的指示执行此操作,则此全局对象仅在外部
函数表达式中可用。它不是真正的全球性的。还请注意,使用“
global
”(小写)非常常见;您可能想考虑一个不同的变量名(也许‘代码>常量< /代码>?)/p>如果对象只是这样的属性集合,您可以用一个对象文字简单地初始化它。不需要调用<代码>新< /代码>。代码>变量全局={…属性…}标记数组:[]、
和否,属性需要值。您可以使用
null
作为替代。您的第二个代码段将不起作用,到处都是打字错误、分号,您必须给出当前的\u标记并验证\u输入值。