2012-10-09 33 views
0

請幫我解決以下問題。在JS功能中獲取來電者姓名

var test = new Object(); 
test.testInner = new Object(); 

test.testInner.main = function() 
{ 
    Hello(); 
} 

function Hello() 
{ 
    /**** Question: currently I am getting blank string with below code, 
    **** Is there any way to get function name as "test.testInner.main" over here? */ 
    console.log(arguments.callee.caller.name); 
} 
test.testInner.main(); 
+0

你可能想看看這個回溯函數:http://snipplr.com/view/23047/ – h2ooooooo

+0

你爲什麼要將調用者的名字寫入日誌而不是使用調試器,並且看着堆棧跟蹤? – PhonicUK

+0

@ PhonicUK,是的。 – SunnyShah

回答

1

test.testInner.main具有anonymous參考(不名)函數。 您可以通過爲其分配名稱來獲取名稱。修改後的代碼:

var test = new Object(); 
test.testInner = new Object(); 

test.testInner.main = function main() 
{ 
    Hello(); 
} 

function Hello() 
{ 
    /**** Question: currently I am getting blank string with below code, 
    **** Is there any way to get function name as "test.testInner.main" over here? */ 
    console.log(arguments.callee.caller.name); 
} 
test.testInner.main(); 

jsfiddle

0

您可以設置在Javascript功能的情況下。

function hello() { 
    console.log(this); 
} 
some.other.object = function() { 
    hello.call(this, arguments, to, hello); 
} 

這將是some.other.object in hello()。

在你的例子中,調用者是main,並且它沒有name屬性,因爲它是匿名的。像這樣:Why is arguments.callee.caller.name undefined?

此外,參數已被棄用,因此不應使用。