2010-01-29 98 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