声明全局变量的正确方法是什么

What is the proper way to declare global variables

我知道吊装。

但我想知道推荐的全局数组解决方案是什么,例如,用作查找 table。在大多数语言中您将声明常量并使其成为全局数组。

喜欢:

 var lookup = ["010101010", "0100101010", "01010101010", "etc"];

 function foo() {    
     // lookup is undefined
 }

我想我可以把它传进去。或者使其成为 window.document 的一部分。或者我不完全理解的 'this' 的一些技巧。执行此操作的最佳方法是什么?

编辑: 是的,看了评论,我现在明白了,我遇到的问题不是吊装引起的。我的代码中还有其他问题。现在可以了。感谢您清理。

只需确保在调用函数 foo 之前声明 lookup。请参阅以下代码段。如果你在调用 foo 之后声明它,你将得到错误 undefined.

var lookup = ["010101010", "0100101010", "01010101010", "etc"];
foo();
 function foo() {    
     console.log(lookup);
 }

如果要存储一些静态数据,使用静态方法:

class CONSTANT {

  /**
   * Public method that will return a new array you can manipulate
   *
   * It's different of this.MY_CONSTANT = [X, Y, Z];
   *
   * Because accessing this.MY_CONSTANT will gives you an access to
   * the same element (if you modify it, it will get
   * modified for the next use of it)
   */
  static get MY_CONSTANT() {
    return [ 
        '010101010', 
        '0100101010',
        '01010101010',
    ];
  }

}

要访问:

CONSTANT.MY_CONSTANT

Ps:需要ES6