Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Scope - including without passing or making global

I'm working on some script for a set of functions that all operate from one call and take a large number of parameters to return one value. The main function requires the use of 11 other functions which need to work with the same parameters. I have it structured somewhat like this:

function mainfunction(param1, param2, ..., param16)
{
    //do a bunch of stuff with the parameters
    return output;
}

function secondaryfunction1()
{
    //gets called by mainfunction
    //does a bunch of stuff with the parameters from mainfunction
}

Is there anything I can do to make the parameters passed to mainfunction available to all the secondary functions without passing them or making them global variables? If not, that's fine, I'll pass them as parameters - I'm curious as to whether or not I can do it more elegantly.

like image 678
Rstevoa Avatar asked Aug 05 '26 17:08

Rstevoa


2 Answers

You can place the definition of secondaryfunction1 inside mainfunction:

function mainfunction(param1, param2, ..., param16){
    function secondaryfunction1() {
     // use param1, param2, ..., param16
    }
    secondaryfunction1();
}

Update:

As @dystroy pointed out, this is viable if you don't need to call secondaryfunction1 somewhere else. Where the list of parameters would be coming from in this case - I don't know.

like image 85
Igor Avatar answered Aug 08 '26 10:08

Igor


You could use arguments to pass to secondaryFunction1 all the arguments of mainfunction. But that would be silly.

What you should probably do, and what is usually done, is embed all the parameters in an "options" object :

function mainfunction(options){
    secondaryfunction1(options);
}

function secondaryfunction1(options) {
     // use options.param1, etc.
}

// let's call it
mainfunction({param1: 0, param2: "yes?"});

This leds to other advantages, like

  • naming the parameters you pass, it's not a good thing for maintenance to have to count the parameters to know which one to change. No sane library would let you pass 16 parameters as direct unnamed arguments to a function
  • enabling you to pass only the needed parameters (the other ones being default)
like image 35
Denys Séguret Avatar answered Aug 08 '26 09:08

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!