简体   繁体   English

如何在Javascript中创建常量文件?

[英]How to create a file of constants in Javascript?

Is there a way to create a file of constants in JavaScript, which I can reference and then use? 有没有办法在JavaScript中创建常量文件,我可以参考然后使用? What I am looking for is something like this: 我正在寻找的是这样的:
Constants.js: Constants.js:

var Phones = var Phones =
{ {
Nokia: 1, 诺基亚:1,
Samsung: 2 三星:2
} }

Then, in another JavaScript file JS2.js access those values: JS2.js: 然后,在另一个JavaScript文件JS2.js中访问这些值:JS2.js:
alert(Phones.Nokia); 警报(Phones.Nokia);

And then, in an aspx file that uses them, reference both of them, like: 然后,在使用它们的aspx文件中,引用它们,例如:
<asp:ScriptReference Path="../js/JS2.js" />
<asp:ScriptReference Path="../js/Constants.js" />

Is such an architecture possible? 这样的架构可能吗? What datatypes can we use? 我们可以使用哪些数据类型? I only exemplified enums because this is what i use right now, but they must be declared in the same file as they are used. 我只举例说明了枚举,因为这是我现在使用的,但它们必须在使用它们的同一文件中声明。

It is very much possible (exactly as you use them). 它非常有可能(就像你使用它们一样)。 It won't be an enum though, just an object with several numeric fields. 它不会是一个枚举,只是一个具有多个数字字段的对象。

You should use the script reference to constants as the topmost one (logically). 您应该使用常量的脚本引用作为最顶层的(逻辑上)。

The common types are: 常见的类型是:

  • undefined (variable) 未定义的变量)
  • null (variable) null(变量)
  • String
  • Boolean 布尔
  • Number
  • String
  • Object 宾语

you're doing it right. 你做得对。

make sure the constants are declared first. 确保首先声明常量。

JavaScript parses alls scripts and script file links in top down order. JavaScript以自上而下的顺序解析所有脚本和脚本文件链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM