Global functions in javascript

I am new to JS and trying to understand global and private functions. I understand global and local variables. But if I have HTML with name test.htmland 2 js files with name test1.jsand test2.js. Now I include test1.jsboth test2.jsin test.htmland call functions written in test2.jsinside test1.jsand test.html.

The functions that I wrote in test2.js are in this form

function abc(){...}

function pqr(){...} etc.

Are these features global? If they are, how can I not make them global and still contact them in test1.jsand test.html?

How did I read global functions or global variables right?

+11
source share
4

JS . , function , window, .. .

"private", , . , , - , , JS , . , , "" .

:

MyObject = {
    abc: function(...) {...},
    pqr: function(...) {...}
    // other functions...
}

abc -, :

MyObject.abc(...);
+15
var SomeName = function() {

    var function1 = function (number) {
        return number+1;
    }

    var anotherFunction = function (number) {
        return number+2;
    }

    return {
        function1: function (number) {
            return function1(number);
        },
        function2: function (number) {
            return anotherFunction(number);
        }
    }
}();

console.log(SomeName.function1 (1));//logs 2

console.log(SomeName.function2 (1));//logs 3

+4

, - , . , , .

:

//these are global variables
foo = 123;
var ABC = 'school';

//these are "private" variables
test = function(){
  var foo = 123
}

(function(){
  var ABC = 'school';
}).call(this);

window, . "" , var. "". foo var .

var foo = 123;
(function(){
  var foo = 987; //this foo is separate from the above foo
}).call(this);

"" , :

window.foo = 123;
(function(){
  window.foo = 123;
}).call(this);

.

, , window.

(function(){

  //all code goes here

  //define global variable
  window.foo = 123;

})call(this);
+2

, , ?

. , - - .

, Javascript, , javascript, html script.

, "" ( RequireJS).

:

var T1 = function() {
   return < some module object >
})(); // notice the parenthesis

Google " Javascript".

. .

+1

All Articles