I want to know if it possible to get the names (not the values) of the function parameters from outside of a function, either with a native JavaScript function/method or something custom.
// function parameters cat, dog, bird
function foo(cat, dog, bird) {};
// now access these names from outside the function, something like (pseudocode)
foo.getFunctionParameters();
or
getFunctionParameters(foo);
Which would log
['cat', 'dog', 'bird']
The reason:
I have an object that has a values
functions. These functions have different function parameters. I must loop through this Object
and execute the function
. I do not want to pass a key
with each Object
that contains the function
, telling me which function parameter
to pass (via an if...else
). I'd simply create an Object
with my possible function parameters
and the use the actual function parameters
to access the needed values
.
const someArray = [
{
foo: [
{
function: (cat, dog) => {...},
otherKeys: otherValues,
},
{
function: (apple, orange) => {...},
otherKeys: otherValues,
},
{
function: (cat, apple) => {...},
otherKeys: otherValues,
},
...
],
...
}
]
Then I'd simply construct an object with the possible function parameters
const possibleFuncParams = {
cat: 'Sweet',
dog: 'More a cat person',
apple: 'I like',
orange: 'not so much',
...
}
And then use the function paramaters
coming back from getFunctionParameters()
to access the object
(something like this):
const keys = getFunctionParameters();
possibleFuncParams[keys[0]];
possibleFuncParams[keys[1]];
What I do not want to do is
const someArray = [
{
foo: [
{
function: (cat, dog) => {...},
otherKeys: otherValues,
keyToSelectFuncParam: 'animals'
},
{
function: (apple, orange) => {...},
otherKeys: otherValues,
keyToSelectFuncParam: 'fruits'
},
{
function: (cat, dog) => {...},
otherKeys: otherValues,
keyToSelectFuncParam: 'mixed'
},
...
],
...
}
]
And then
if(keyToSelectFuncParam === 'animals') {
foo.functio('Sweet', 'More a cat person');
}