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

Best practice for "global" variables in JavaScript?

本文关键字:最佳 变量 全局 JavaScript      更新时间:2023-09-26

我把我所有的代码都放在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
}

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

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"?