How to store javascript variables?
I am currently coding in this way:
<script type="text/javascript"> var linkObj; Is this a safe way to store data? I am worried that if jQuery or another plugin should also use the linkObj variable. Also, if I declare my variable like this, then can it also be seen by other functions in scripts located in other js files that I include?
I declare the variable in such a way that it will be available for all scripts running on the page.
If you just want to use it locally, wrap it in a function:
(function() {var linkObj; ... })() However, this way nothing outside the function can access it.
If you want to explicitly pass certain variables between different scripts, you can also use the object as a namespace:
var myProject = {} myProject.linkObj = ... This minimizes the number of global names you should rely on.
Is this a safe way to store data?
This is not storing data as such, but only declaring a variable in a script block in what I assume is an HTML page. When you reload the page in the future, it will not save the previous values.
My concern is that if jQuery or another plugin should also use the linkObj variable.
This is a fair concern, like others. However, you expect plugins to not rely on volume outside the plugin. This should not greatly affect the fact that a good plugin design is likely to prevent this.
Also, if I declare my variable like this, then can it also be seen by other functions in scripts located in other js files that I include?
Yes. While their execution starts after loading the script block. This usually follows the order in which your script declaration appears on the page. Or regardless of the order that they display on the page if they are executed, for example, after the jQuery DOM "ready" event.
It is well known that it is good to avoid "global pollution of the namespace", which is associated with this problem. To do this, you can use the function to contain the code and directly call this function in your script block.
(function () { var a = 1; // the scope is within the function alert('The variable a is equal to: ' + a); }) (); // the parenthesis invoke the function immediately