If开发者_开发百科 I have two js files that contain variables with the same name, can I use both of the files at the same time? Would those variables cause conflicts?
Thanks.
Yes, global variables are as their name implies, global. Thus:
//file1.js
x = 10;
//file2.js
alert(x); //will alert 10
As long as both files are included in the same page.
Yes, the variable that is declared afterwards would overwrite the variable that is declared first.
Imagine your external Javascript as just being embedded inside the <script></script> that references it.
So if you had this code (assuming that script1, script2, and script3 are included in that order):
// script1.js
var x = 1;
var y = 2;
// script2.js
var x = 2;
// script3.js
alert(x); // 2
Whereas if script2 and script1 swapped places in their order, script3 would alert "1".
As long as they are different files, you're safe. Even a file1.js?4
and file1.js?5
works at the same location...the server might return something different with a different query string.
Example:
<script type="text/javascript" src="scripts/file1.js?v=5">
<script type="text/javascript" src="scripts/file1.js?v=6">
They might be 2 complete different files, and if so that's fine, they'll both run. The same name isn't a problem, the same actual file might cause some weird behavior, like event handlers being hooked up and firing twice, etc.
They will not cause a conflict. Obviously they have to be in different locations.
<script src="scripts1/file.js">
<script src="scripts2/file.js">
Should be just fine.
精彩评论