Make javascript variable available only for functions in one .js file

I am somewhat new to Javascript and I am stuck on this one element. Can someone please show me how to make the javascript variable available only in the .js file that it is included.

Example:

Let's say I have two .js files, PG1 and PG2. PG1 contains var channel = Channel01;

PG2 contains a variable with the same name, but another variable entered (part after the equal sign) (var channel = Channel02)

I don't want function1 on PG1 to use a variable on PG2 or for function2 on PG2 to use a variable on PG1.

I also call these functions from a separate HTML page.

Problem. All my functions end up using only one variable no matter what page they are on. (e.g. function1 and function2 use var var = channel01)

Question: How to restrict functions on page1 to use only variables on this .js page

Thank!

+3
source share
4 answers

module template:

var myModule = (function(exports){

    var x = "foo";

    exports.myFunction = function(){
        alert(x);
    };

})(typeof exports!="undefined" && exports instanceof Object ? exports : window );

myFunctionwill be available in the area windowin the browser.

EDIT

I quote the author: "I also call these functions from a separate HTML page."

therefore, the author needs global access to the functions he defines.

var myModule is not needed, although it is not exported, it is just for compatibility with AMD:

(function(exports){

    var x = "foo";

    exports.myFunction = function(){
        alert(x);
    };

})(window);

x myFunction , myFunction x . x - x = "foo"

+4

, .

(function() {
   // Your file contents live here.
})();
+6

- , JavaScript IIFE. . , , , .

(function() {
    var channel = Channel01;

    // Put the rest of your PG1 code here, for example:

    function init() {
        channel.open();
    }

    init();
})();

You can then wrap your PG2 code in IIFE in the same way. The result will be that the two scenarios have no variables other than global variables already set, such as Channel01and Channel02.

+3
source

Although this is not a direct answer to your question, it is connected and important, since its absence can contaminate other modules. If you do not use the var keyword, the variable is in the global scope ie

(function () {
   x = 'foo'; //x is on the global scope and can be seen everywhere
})()

(function () {
   var y = 'bar'; //y is local to this function
})()

I hope that I did not have a duplication of what someone said above, but I could not see it.

+1
source

All Articles