Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global functions in javascript

Tags:

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?

like image 554
ugandajs Avatar asked Apr 08 '15 12:04

ugandajs


People also ask

What is a global function?

Global functions are custom functions that can be called from custom actions configured for request, change, or custom schedules, whenever necessary.

How do you write a global function in JavaScript?

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.

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.

How do you declare a global 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.


1 Answers

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(...); 
like image 140
Marko Gresak Avatar answered Nov 09 '22 16:11

Marko Gresak