1

I know I can get the String representation of a function without calling it like this

function storeData(id, data) { console.log("Doing stuff..") };
storeData.toString(); //"function storeData(id, data) { console.log("Doing stuff..") }"

And I could in theory parse the resulting String to pull out the variable names. Any takers on writing that code? Is there an easier way? (I don't need to worry about minification)

Niko Bellic
  • 2,370
  • 2
  • 29
  • 25
  • 3
    What is the problem you're trying to solve? – Pointy Aug 20 '15 at 01:41
  • 2
    As pointed out by Pointy (haha, I couldn't resist), this looks like a case of [XY problem](http://meta.stackexchange.com/a/66378/302323). And a duplicate of http://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically-from-javascript – Domino Aug 20 '15 at 01:45
  • I'm trying to create a GUI that allows people invoke functions by entering parameters into input boxes and then invoking the function with a button. It would be nice to show the user the name of the inputs. However, this is hard because the functions are arbitrary. Getting the function name programmatically during run-time is easy since they are properties on an object and I can inspect the object keys using (for .. in ), but I also need the parameter names. – Niko Bellic Aug 20 '15 at 01:49
  • @JacqueGoupil, you are right, this is a duplicate. Apologies. I'm going to flag for close/deletion. – Niko Bellic Aug 20 '15 at 01:58

1 Answers1

3

try to use the following code:

  var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  var ARGUMENT_NAMES = /([^\s,]+)/g;
  function getParamNames(func) {
      var fnStr = func.toString().replace(STRIP_COMMENTS, '');
      var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
      if (result === null)
          result = [];
      return result;
  }

  getParamNames(getParamNames) // returns ['func']
  getParamNames(function (a, b, c, d) { }) // returns ['a','b','c','d']
  getParamNames(function (a,/*b,c,*/d) { }) // returns ['a','d']
  getParamNames(function () { }) // returns []
Allan Chua
  • 9,305
  • 9
  • 41
  • 61