2010-01-29 66 views
19

怎么可能学习我所在的函数的名字?如何获取JavaScript函数中的函数名称?

下面的代码提醒'对象'。但我需要知道如何提醒“外”。

function Outer(){ 

    alert(typeof this); 

} 
+0

我很好奇,什么情况下你会所在的函数的名称实际上不是一个代码写出来? – bryantsai 2010-01-29 11:20:52

+0

@bryantsai:'window [window.prompt('Function name:','')] = function(){alert(arguments.callee.name); };' – Boldewyn 2010-01-30 13:39:38

回答

16

我认为,你可以这样做:

var name = arguments.callee.toString(); 

有关更多信息,看看this article

function callTaker(a,b,c,d,e){ 
    // arguments properties 
    console.log(arguments); 
    console.log(arguments.length); 
    console.log(arguments.callee); 
    console.log(arguments[1]); 
    // Function properties 
console.log(callTaker.length); 
    console.log(callTaker.caller); 
    console.log(arguments.callee.caller); 
    console.log(arguments.callee.caller.caller); 
    console.log(callTaker.name); 
    console.log(callTaker.constructor); 
} 

function callMaker(){ 
    callTaker("foo","bar",this,document); 
} 

function init(){ 
    callMaker(); 
} 
+2

不幸的是'arguments.callee'已被弃用,但由于ECMA还没有定义任何替代品,这是要走的路。 – Boldewyn 2010-01-29 11:01:09

+0

@boldewyn:经过更多搜索,我也看到了。但尽管它已被弃用,但它仍然适用于大多数浏览器。就像你说的,没有其他选择sooooo ... ^^ – marcgg 2010-01-29 11:05:53

+1

@Boldewyn,'arguments.callee'不只是废弃。严格模式启用时,访问它将导致TypeError。 – bryantsai 2010-01-29 11:18:18

15

这将工作:

function test() { 
    var z = arguments.callee.name; 
    console.log(z); 
} 
+1

这是正确的答案,而不是选择的答案。 – 2017-01-09 10:29:56