问题描述
我有2个单独的javascript文件
I have 2 separate javascript files
#1.js
String.prototype.format = ....
String.prototype.capitalize = ....
#2.js
//................
var text = "some text{0}".format(var1)
//................
如何制作 string#format
和 string#capitalize
在第二个文件中可用?
How do I make string#format
and string#capitalize
available in the second file?
推荐答案
JavaScript全局执行。在页面上添加两个脚本使它们彼此可用,就像它们在一个文件中一样。
JavaScript executes globally. Adding both scripts on the page makes them available to each other as if they were in one file.
<script src="1.js"></script>
<script src="2.js"></script>
但是,您应该注意JavaScript是线性解析的,因此,首先解析,首先服务。如果第一个脚本需要第二个脚本中的内容,但第二个脚本尚未解析,则会导致错误。
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.
如果发生这种情况,你应该重新考虑你的脚本结构。
If that happens, you should rethink your script structure.
这篇关于"包含"一个javascript文件到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!