Global functions in javascript

ugandajs picture ugandajs · Apr 8, 2015 · Viewed 93.2k times · Source

I'm new to js and trying to understand global and private functions. I understand global and local variables. But if I have an html named test.html and a 2 js files named test1.js and test2.js. Now I include the test1.js and test2.js in test.html and call the functions written in test2.js inside test1.js and test.html.

The functions that I have written in test2.js are in this form

function abc(){...}

function pqr(){...} etc.

are these above functions global? If they are , how can I not make them global and still access them in test1.js and test.html?

As I have read global functions or global variables are bad right?

Answer

Marko Grešak picture Marko Grešak · Apr 8, 2015

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(...);