Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
JS Introspection: extract function parameter names
Function.prototype.argNames = function () {
// Extract function string representation: hopefully we can count on it ?
var s = this.toString();
// The cool thing is: this can only be a syntactically valid function declaration
s = s // "function name (a, b, c) { body }"
.substring( // "a, b, c"
s.indexOf('(')+1, // ----------------^
s.indexOf(')') // ------^
// Cleanup the string, ignore spaces and linefeeds, only identifiers matter
s = s.replace(/[\r\n\s]*/g, ''); // "a,b,c"
// Let's be ES6-ready: any argument can be followed by '= default value'
s = s // a,b="\"toto\"",c='hello',d=3342,e,f
.replace(/\\+['"]/g, '') // a,b="toto",c='hello',d=3342,e,f
.replace(/=\s*(["']).*?\1/g, '') // a,b,c,d=3342,e,f
.replace(/=.*?(,|$)/g, '') // a,b,c,d,e,f
return s.split(','); // ["a", "b", "c"]

This comment has been minimized.

Copy link

@xcombelle xcombelle commented Oct 22, 2013

this can be tricked by putting comments in argnames

(function (a,b/*, c*/) {}).argNames() 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment