Some time ago I made this class that exports 2 methods: One that returns the name of the function (the name in the declaration)
getFunctionName(function myFunction(a, b, c){})
that returns "myFunction" or an empty string if it is an anonymous function.
and this one that returns the name of the parameters:
getParameterNames(function myFunction(a, b, c){})
that returns "[a, b, c]"
Keep in mind that if you use it like this:
var fn = function myFunction(a, b, c) {};
getFunctionName(fn);
It also returns myFunction
, since it takes into account the declaration of the function, not the alias with which it is passed. Therefore it will not work as you ask, but it is what can be done in javascript.
These methods basically parse the function to obtain the data (use function.toString
to do it). Includes some ECMAScript 2015 support.
var reflection = (function () {
'use strict';
var stripComments = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
argumentNames = /([^\s,]+)/g,
reflection = {};
/**
* Checks if 'expr' is a function
* @param {} expr
* @returns {}
*/
function isFunction(expr) {
return typeof expr === 'function';
}
/**
* Gets the function parameter names as an Array.
*
* usage example: getParameterNames(function (a,b,c){}); // ['a','b','c']
* @param {} func the function.
* @returns {} An ordered array of string with the parameters names, or an empty array if the function has no parameters.
*/
function getParameterNames(func) {
var fnStr = func.toString().replace(stripComments, '');
var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(argumentNames);
if (result === null)
result = [];
return result;
}
/**
* Gets the function name.
*
* @param {} func the function.
* @returns {} the name of the function, empty string if is an anonymous function.
*/
function getFunctionName(func) {
if (!isFunction(func)) throw new TypeError('"func" must be a function.');
// ECMAScript 2015
if (func.name) {
return func.name;
}
// old fashion way
var fnStr = func.toString().substr('function '.length),
result = fnStr.substr(0, fnStr.indexOf('('));
return result;
}
// Module Exports
reflection.isFunction = isFunction;
reflection.getFunctionName = getFunctionName;
reflection.getParameterNames = getParameterNames;
return reflection;
}());