Get Function Parameter List With JavaScript

JavaScript has great potential in terms of metaprogramming capabilities. Check out the methods in this article to find out how to get a parameter list for any function.

Function.prototype.contents = function(){
  return this.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]
}

Function.prototype.params = function(){
  return this.toString().match(/\((.*?)\)/)[1].match(/[\w]+/g) || []
}

var username = function(first, last){
  return 'foo'
}

print(username.contents())  // => "return 'foo'; "
print(username.params()) // => ['first', 'last']

Comments

Also getName, for Browsers that don't support function.name (I'm looking at you, IE).

Function.prototype.getName = function() { return this.name || this.toString().match(/^function\s*(.*)\(/)[1] }

Ya its unfortunate hey? thats the only thing I dont like about Javascript, the metaprogramming is always a bit of a hack

I originally had used this concept for the JSocka framework - however, you run up against the wall that base Javascript classes and functions don't reveal their source code.

I'd kill to see this stuff opened up.