[英]How to use javascript constant in javascript file from another javascript file
I have created one javascript file in which I have declared different string constants.我创建了一个 javascript 文件,在其中声明了不同的字符串常量。
now in another javascript file I want to use those String constants from already created javascript file.现在在另一个 javascript 文件中,我想使用已经创建的 javascript 文件中的那些字符串常量。
Is there any way to do this.有没有办法做到这一点。
Thanks in advance.提前致谢。
If you declare your constants in file1
as global variables:如果将
file1
的常量声明为全局变量:
var someConstant = 42;
Then you can just use that variable in your other JS files.然后您就可以在其他 JS 文件中使用该变量。 Just make sure
file1
is loaded before you try to use them.在尝试使用它们之前,请确保加载了
file1
。
However, polluting the global scope like this come with it's risks , as those variables are easily changed.然而, 像这样污染全局范围是有风险的,因为这些变量很容易改变。
Multiple ways.多种方式。
Use a task runner like grunt to define a task that concatenates your files into a single one.使用像grunt这样的任务运行器来定义一个将您的文件连接成一个的任务。 This will not only allow convenient definition of constants but also improve performance.
这不仅可以方便地定义常量,还可以提高性能。
There are other tools to do this, too.还有其他工具可以做到这一点。 See Prepros for windows and codekit for Macs.
请参阅适用于 Windows 的Prepros和适用于 Mac 的codekit 。
If you are on client side, use a tool like require.js or browserify to define commonJS / AMD modules and require them as you need.如果您在客户端,使用像一个工具require.js或browserify定义CommonJS的/ AMD模块,并要求他们为你所需要的。
If you are on server side using node, this works out of the box for commonJS.如果您在服务器端使用 node,这对于 commonJS 来说是开箱即用的。
You could load your constant defining script first and do something like this:您可以先加载常量定义脚本并执行以下操作:
var constants = {
MY_CONST: 'Foo'
}
Your main, whi script could access this variable.您的主要 whi 脚本可以访问此变量。 If you omit the
var
keyword, the variable becomes globally available.如果省略
var
关键字,该变量将变为全局可用。 Note however that this should be avoided.但是请注意,应该避免这种情况。
You could even add a property to the global object ( window
on the client side).您甚至可以向全局对象(客户端的
window
)添加一个属性。
Personally I like to use commonJS modules when working on projects that allow me to do so.我个人喜欢在处理允许我这样做的项目时使用 commonJS 模块。 Rob Ashton has an opinion on this that I would like to share.
Rob Ashton对此有一个我想分享的观点。
When I can't use those modules in a convenient way, which would be the case when working with (custom) web-components because of their isolated scopes, I like to add a single script which creates an Object like App
.当我无法以方便的方式使用这些模块时,在使用(自定义)Web 组件时就是这种情况,因为它们的作用域是独立的,我喜欢添加一个脚本来创建像
App
这样的对象。 I use this object to expose modules, services & constants which can then be required by any component in a neat way:我使用这个对象来公开模块、服务和常量,然后任何组件都可以以一种简洁的方式需要它们:
App.myService.doSomething()
Constants.js常量.js
const EMAIL = "xyz@gmail.com"
const PHONE = "9911223344"
var NAME = "Default name"
xyz.html xyz.html
<script src="Constants.js"></script>
只需使用它,并确保在第一个开头引用具有所有常量的 javascript 文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.