Quiero saber si es posible obtener los nombres (no los valores) de los parámetros de la función desde fuera de una función, ya sea con una función/método de JavaScript nativo o algo personalizado.
// function parameters cat, dog, bird function foo(cat, dog, bird) {}; // now access these names from outside the function, something like (pseudocode) foo.getFunctionParameters();o
getFunctionParameters(foo);que registraría
['gato', 'perro', 'pájaro']
La razón: tengo un objeto que tiene funciones de values . Estas funciones tienen diferentes parámetros de función. Debo recorrer este Object y ejecutar la function . No quiero pasar una key con cada Object que contiene la function , diciéndome qué function parameter pasar (a través de un if...else ). Simplemente crearía un Object con mis posibles function parameters y usaría los function parameters reales para acceder a los values necesarios.
const someArray = [ { foo: [ { function: (cat, dog) => {...}, otherKeys: otherValues, }, { function: (apple, orange) => {...}, otherKeys: otherValues, }, { function: (cat, apple) => {...}, otherKeys: otherValues, }, ... ], ... } ]Entonces simplemente construiría un objeto con los posibles parámetros de función
const possibleFuncParams = { cat: 'Sweet', dog: 'More a cat person', apple: 'I like', orange: 'not so much', ... } Y luego use los parámetros de function paramaters que regresan de getFunctionParameters() para acceder al object (algo como esto):
const keys = getFunctionParameters(); possibleFuncParams[keys[0]]; possibleFuncParams[keys[1]];lo que no quiero hacer es
const someArray = [ { foo: [ { function: (cat, dog) => {...}, otherKeys: otherValues, keyToSelectFuncParam: 'animals' }, { function: (apple, orange) => {...}, otherKeys: otherValues, keyToSelectFuncParam: 'fruits' }, { function: (cat, dog) => {...}, otherKeys: otherValues, keyToSelectFuncParam: 'mixed' }, ... ], ... } ]Y entonces
if(keyToSelectFuncParam === 'animals') { foo.functio('Sweet', 'More a cat person'); }Lo conseguí googleando... pruébalo
// JavaScript program to get the function // name/values dynamically function getParams(func) { // String representaation of the function code var str = func.toString(); // Remove comments of the form /* ... */ // Removing comments of the form // // Remove body of the function { ... } // removing '=>' if func is arrow function str = str.replace(/\/\*[\s\S]*?\*\//g, '') .replace(/\/\/(.)*/g, '') .replace(/{[\s\S]*}/, '') .replace(/=>/g, '') .trim(); // Start parameter names after first '(' var start = str.indexOf("(") + 1; // End parameter names is just before last ')' var end = str.length - 1; var result = str.substring(start, end).split(", "); var params = []; result.forEach(element => { // Removing any default value element = element.replace(/=[\s\S]*/g, '').trim(); if (element.length > 0) params.push(element); }); return params; } // Test sample functions var fun1 = function(a) {}; function fun2(a = 5 * 6 / 3, // Comment b) {}; var fun3 = (a, /* */ b, //comment c) => /** */ {}; console.log(`List of parameters of ${fun1.name}:`, getParams(fun1)); console.log(`List of parameters of ${fun2.name}:`, getParams(fun2)); console.log(`List of parameters of ${fun3.name}:`, getParams(fun3));