“包含”一个javascript文件到另一个[重复]

时间:2022-04-01 22:58:10

This question already has an answer here:

这个问题在这里已有答案:

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#format and string#capitalize available in the second file?

如何在第二个文件中使用string#format和string#capitalize?

1 个解决方案

#1


43  

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.

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

#1


43  

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.

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