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

时间:2012-04-09 17:04:25

标签: javascript

我将所有代码都放在NS中,类似于jQuery的结构。我有一些全局的NS变量,我希望将其包含在内,然后像这样访问 - > Global.variable_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
}

1 个答案:

答案 0 :(得分: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对象仅在该外部Arc函数表达式中可用。这不是真正的全球化。另请注意,使用'global'(小写)非常常见;你可能想要考虑一个不同的变种名称(也许是'constants'?)

相关问题