有没有办法在javascript中确定哪个函数名为myFunction?

时间:2012-04-04 02:11:35

标签: javascript

  

可能重复:
  Determine calling function in javascript

假设我在javascript中有一个函数,我想知道谁是调用者。如果不使用全局变量/参数方法,这可能吗?

1 个答案:

答案 0 :(得分:0)

要与多种浏览器兼容,您需要以下内容:

if (typeof arguments.caller == 'function') {
  return arguments.caller;

} else if (typeof arguments.callee == 'function' && 
           typeof arguments.callee.caller == 'function') {
  return arguments.callee.caller;

} else {
  // called from global scope, in strict mode or browser doesn't support
  // either of the above access methods
}

请注意,访问arguments.callee或caller将在ES5严格模式下抛出异常,上面可能会避免这种情况,但我现在无法测试它。

相关问题