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?
Global functions are custom functions that can be called from custom actions configured for request, change, or custom schedules, whenever necessary.
This "window" object is accessible to all JavaScript code of a page, even if it's an external file. So, if the "window" object is global, then the functions it contain will also be global. So, if we add a new function to the "window" object, it will be a global function.
There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
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(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With