In ES6, you can just use myFunction.name
.
Note: Beware that some JS minifiers might throw away function names, to compress better; you may need to tweak their settings to avoid that.
In ES5, the best thing to do is:
function functionName(fun) {
var ret = fun.toString();
ret = ret.substr('function '.length);
ret = ret.substr(0, ret.indexOf('('));
return ret;
}
Using Function.caller
is non-standard. Function.caller
and arguments.callee
are both forbidden in strict mode.
Edit: nus's regex based answer below achieves the same thing, but has better performance!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…