37

I have 2 separate javascript files

#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?

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205
  • In what environment? A browser? Command-line? A server? – T.J. Crowder Feb 28 '13 at 12:40
  • 2
    This has been asked and answered ***several*** times now, [notably here](http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file), just look at the "Related" list on the right (it would also have been "pushed" at you when you were asking the question). – T.J. Crowder Feb 28 '13 at 12:42

1 Answers1

45

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>

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.

Joseph
  • 117,725
  • 30
  • 181
  • 234