Skip to content

Instantly share code, notes, and snippets.

@naholyr
Created February 19, 2012 18:30
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save naholyr/1865010 to your computer and use it in GitHub Desktop.
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"]
};
@xcombelle
Copy link

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