“包含”一个 javascript 文件到另一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15135718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:38:14  来源:igfitidea点击:

"Include" one javascript file to another one

javascript

提问by Alan Coromano

I have 2 separate javascript files

我有 2 个单独的 javascript 文件

#1.js
String.prototype.format = ....
String.prototype.capitalize = ....

#2.js

//................
var text = "some text{0}".format(var1)
//................

How do I make string#formatand string#capitalizeavailable in the second file?

我如何制作string#formatstring#capitalize在第二个文件中可用?

回答by Joseph

JavaScript executes globally. Adding both scripts on the page makes them available to each other as if they were in one file.

JavaScript 全局执行。在页面上添加这两个脚本使它们彼此可用,就像它们在一个文件中一样。

<script src="1.js"></script>
<script src="2.js"></script>

However, you should note that JavaScript is parsed "linearly" and thus, "first parsed, first served". If the first script needs something in the second script, but the second script hasn't been parsed yet, it will result in an error.

但是,您应该注意 JavaScript 是“线性”解析的,因此是“先解析,先服务”。如果第一个脚本需要第二个脚本中的某些内容,但第二个脚本尚未解析,则会导致错误。

If that happens, you should rethink your script structure.

如果发生这种情况,您应该重新考虑您的脚本结构。