Javascript – How to get the function name from within that function

functionjavascript

How can I access a function name from inside that function?

// parasitic inheritance
var ns.parent.child = function() {
  var parent = new ns.parent();
  parent.newFunc = function() {

  }
  return parent;
}

var ns.parent = function() {
  // at this point, i want to know who the child is that called the parent
  // ie
}

var obj = new ns.parent.child();

Best Answer

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!