Global functions in javascript Global functions in javascript javascript javascript

Global functions in javascript


Everything in JS is bound to containing scope. Therefore, if you define a function directly in file, it will be bound to window object, i.e. it will be global.

To make it "private", you have to create an object, which will contain these functions. You are correct that littering global scope is bad, but you have to put something in global scope to be able to access it, JS libraries do the same and there is no other workaround. But think about what you put in global scope, a single object should be more than enough for your "library".

Example:

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

To call abc for somewhere, be it same file or another file:

MyObject.abc(...);


Anything defined in a file without any sort of wrapper will be bound to the window object. Anything bound to the window object is global.

Example:

//these are global variablesfoo = 123;var ABC = 'school';//these are "private" variablestest = function(){  var foo = 123}(function(){  var ABC = 'school';}).call(this);

Since global variables in every file will be part of the window object, you can access them between files. It is important when creating "private" variables you add var. This says override any global variables in the current "wrapper". If I have a global variable foo and I define it again in a function with var they will be separate.

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

If you do have a "wrapper" and you want to define a global function you can do it like this:

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

Both functions will do the same thing.

Personally, I prefer to put everything in a wrapper and only define global variables when I need them using window.

(function(){  //all code goes here  //define global variable  window.foo = 123;})call(this);


in test2.js you can write this to make the function global

window.abc = function(){...}

and then in test1.js yo can access it like this

window.parent.abc();

I hope it will help you