Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make A javascript variable only avaliable to functions on the same .js file

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!

like image 816
user1402171 Avatar asked Nov 30 '22 14:11

user1402171


2 Answers

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.
})();
like image 198
alex Avatar answered Dec 06 '22 03:12

alex


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"

like image 24
mpm Avatar answered Dec 06 '22 03:12

mpm