Often I will have a JavaScript file that I want to use which requires certain variables be defined in my web page.
So the code is something like this:
<script type="text/javascript" src="file.js"></script> <script type="text/javascript"> var obj1 = "somevalue"; </script>
But what I want to do is:
<script type="text/javascript" src="file.js?obj1=somevalue&obj2=someothervalue"></script>
I tried different methods and the best one yet is to parse the query string like this:
var scriptSrc = document.getElementById("myscript").src.toLowerCase();
And then search for my values.
I wonder if there is another way to do this without building a function to parse my string.
Do you all know other methods?
You cannot pass variables from one js file to the other Javascript variables are stateless so they wont be retained. If you are using . Net then you can make use of Session variables to solve this purpose. If you use MVC you can go for viewbag or viewdata.
In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.
I'd recommend not using global variables if possible. Use a namespace and OOP to pass your arguments through to an object.
This code belongs in file.js:
var MYLIBRARY = MYLIBRARY || (function(){ var _args = {}; // private return { init : function(Args) { _args = Args; // some other initialising }, helloWorld : function() { alert('Hello World! -' + _args[0]); } }; }());
And in your html file:
<script type="text/javascript" src="file.js"></script> <script type="text/javascript"> MYLIBRARY.init(["somevalue", 1, "controlId"]); MYLIBRARY.helloWorld(); </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With