Can global constants be declared in JavaScript?

前端 未结 8 833
耶瑟儿~
耶瑟儿~ 2020-12-16 09:33

If so, what is the syntax for such a declaration?

8条回答
  •  無奈伤痛
    2020-12-16 09:57

    Everything is global unless declared with the var keyword.

    There are no constants either. You can simply declare them without the var keyword.

    If you want to ensure global scope you can throw it into the window object:

    window.GLOBAL_CONSTANT = "value";
    

    You can do this from within any scope. Constants can then be declared inside functions or closures, though I wouldn't recommend that.

提交回复
热议问题