I somewhat new to Javascript and I'm stuck on this one item. Can someone please show me how to make a javascript variable only usable on the .js file that it is on.
EXAMPLE:
Say I have two .js files, PG1 & PG2. PG1 contains var channel = Channel01;
PG2 contains a variable with the same name, but a different entered Variable (the part after the equals sign) (var channel = Channel02)
I don't want function1 on PG1 to use the variable on PG2 or for function2 on PG2 to use the variable on PG1.
I am also calling these functions from a seperate HTML page.
Problem: All of my functions end up using only one variable no matter what page they are on. (ex. function1 & function2 both use var channel = channel01)
Question: How can I limit functions on page1 to use only the variables on that .js page
Thanks!
Wrap the whole thing in an Immediately Invoked Function Expression, which will effectively give the file its own scope.
(function() {
// Your file's contents live here.
})();
module pattern :
var myModule = (function(exports){
var x = "foo";
exports.myFunction = function(){
alert(x);
};
})(typeof exports!="undefined" && exports instanceof Object ? exports : window );
myFunction
will be available in the window
scope in the browser.
EDIT
i quote the author : "I am also calling these functions from a seperate HTML page."
so the author needs a global access to the functions he defines.
var myModule is not needed though , nor export , it is just for AMD compatibility :
(function(exports){
var x = "foo";
exports.myFunction = function(){
alert(x);
};
})(window);
now x for myFunction only exists in the closure , but myFunction can still access x in the global scope. any x definition in the global scope or whatever scope will not affect x = "foo"
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