0

I'm a complete newbie to Javascript so I don't know what its capable of. Any help would be much appreciated!

As the title suggests, I'm trying to pass an argument from a function to name another function inside of it. The method below doesn't work for obvious reasons but I think it conveys what I'm trying to do. The function names need to be very specific for the project I'm working on.

function mainFunc(param1) {
  function param1() {}
}

Thanks!

Edit: The software that we are going to start using to go paperless at my work uses a javascript scripting engine. In order for me to do simple things such as:

If at least one of the checkboxes in section A is checked, then you must check at least one checkbox in section B.

I would have to write a function for each and every checkbox field on the form due to the way the software works, the function name has to be specific to the name we assign to the checkbox through their GUI. I was hoping to write a function that writes another function with the specific name, and calls the said function.

function mainFunc(funcName) {
  function 'funcName'() {
    //do stuff;
    }
    
  'funcName'()

}


mainFunc('Checkbox1')

Maybe this will help clarify a little more on what I'm trying to do. Sorry for not being clear the first time around.

nattroj
  • 21
  • 3
  • 3
    A function doesn't care what its name is. And a local function nested inside another function isn't visible anywhere else. There is no reason you would ever want to do what you describe in the question. Could you discuss what it is that you _really_ want to accomplish? Otherwise you will just get answers like the ones posted so far, that have some helpful ideas but may or may not be at all relevant to your actual goal. – Michael Geary Dec 30 '17 at 08:19

1 Answers1

0

You have many options to solve your problem

one option is to return an object with the functions named using the parameters passed to mainFun look at the example below

function mainFunc(param1,param2) {
    return {
        [param1]:function () {
            console.log(" I am  function from " + param1)
        },
        [param2] : function () {
            console.log("I am function from " + param2) ;
    }
    }
}
let hello  = 'hello' ;
let greet = 'anything' ;
let functions = mainFunc(hello,greet);
functions['hello']();
functions['anything']();
functions[hello]();
functions[greet]();

if you have many parameters to the mainFun you can also solve it using the arguments object like the example below

function mainFun(par1) {
    let myObj = {};
    for(let i = 0 ; i<arguments.length;i++){
        console.log(arguments[i]);
        myObj[arguments[i]] = ()=> {
            console.log('You call me from ' + arguments[i]);
        }
    }
    return myObj ;
}
let functions  = mainFun('a','b','c','d');
functions['a']();
functions['b']();
functions['c']();
functions['d']();
mostafa tourad
  • 4,308
  • 1
  • 12
  • 21