I am thinking about the correct programming approach:
As I write my JavaScript code, I refer to many dynamically created global objects and variables from within my functions and objects, although I did not pass them as function arguments. This way, I am losing function versatility and independence, as the functions and objects depend on another global objects in my application. I am aware of this fact, however, my objects/functions often need many variables to work with.
Would you advice, whether I should always strive to pass all the variables and objects as function arguments? This way it will be clear, what variables the function needs, and if I supply the correct arguments, the function will always work
Alternatively, don’t I need to be so strict, and as long as my functions/object work, despite they refer to global objects, do not I need to bother with this question anymore?
I need to know correct programming approach, so I do not get used to wrong things.
Yes you want to use global variables as little as possible. If as a result you find that you’re passing a lot of parameters into each function then you should look at the parameters and ask what they have in common. Quite often, adding additional objects helps. You can combine parameters into instance variables of an object and pass the one object. Then, rather than extracting the instance variables, you delegate operations to that object.
For example, suppose you have the following code:
You can create a Point to hold the x,y values and a graphics context to hold the thickness, color and canvas. The resulting call becomes:
You’ve reduced the number of parameters and created reusable objects that contain commonly used operations.