2012-12-07 49 views
1

可能重複:
Can I get the name of the currently running function in javascript?從功能獲取函數名本身

我想從功能本身的功能名稱。

的Javascript:

Cube : { 
    profile : { 
     edit : function(){ 
      // Get function Path Cube.edit Here 
      alert(arguments.callee.name); // Not Working 
     } 
    } 
} 
+0

你可以給你的函數命名:'edit:function edit(){...}' – elclanrs

+0

@Osiris我會經歷這個問題。但我沒有得到我的答案。 'alert(arguments.callee.name);'不適用於上面的代碼示例。 –

+0

@elclanrs:在IE8及更早版本上創建了[兩個函數](http://blog.niftysnippets.org/2010/09/double-take.html)。 –

回答

8

在你的代碼的函數片斷,沒有名字,它是匿名的。它分配給profile的房產有一個名稱(edit),但該功能沒有。不,沒有辦法從函數對象獲取editprofile.editCube.profile.edit

,您可以給函數名稱:

Cube : { 

    profile: { 
     edit : function edit(){ 

     alert(arguments.callee.name); 

     } 
    } 
} 

...那是用命名的函數表達式這將創造two separate function objects在IE8和更早版本。您正在使用arguments.callee這既是對很多瀏覽器的速度很慢

  1. 你也可以這樣做:

    Cube : { 
    
        profile: { 
         edit : Cube_profile_edit 
        } 
    } 
    // ... 
    
    function Cube_profile_edit(){ 
    
        alert(arguments.callee.name); 
    } 
    

    然而,在所有的上述兩個問題,並且在strict mode中無效。

  2. 函數對象的name屬性是非標準的,這就是爲什麼關於可能不必解析的Function#toString結果this answer會談。問題是,Function#toString非標準(但相當廣泛的支持,除了在移動瀏覽器)。

你可能避免第二個問題,通過爲是指功能屬性的Cube對象圖搜索,但仍然需要使用arguments.callee(除非你給功能的真實姓名,然後用真正的名稱搜索時找到導致它的屬性路徑)。