views:

18

answers:

2

We have an HTML page with some global JavaScript variables. We have some utility functions that manipulate these variables. Can you move these util functions to a separate JavaScript file and include the file using the <script> tag? Wasn't sure if the functions in the external file could get/set the global variables that are defined in the main page?

A: 

Unfortunately yes. The whole problem with the global object is that it's "too global" exposing your site to many security risks.

A better idea would be to encapsulate data and methods into objects.

galambalazs
What's an example of using objects for this use case?
Marcus
The data and the methods belong to one can be gathered into an object. http://en.wikipedia.org/wiki/Object-oriented_programming
galambalazs
A: 

Yes, you can do so by all means. All scripts referenced by the same HTML page have access to the same set of global variables and functions. Just keep in mind that the scripts are included in the order in which they appear.

casablanca