2013-04-04 81 views
1

我想編寫一個附加功能的名稱#trace每當它被稱爲常規:你如何命名一個函數,以便你可以反思它?

;(function($, window, undefined) { 
    var dom = {}; 
    var myObject = {}; 
    myObject.myFunction = { 
     trace('myObject.myFunction'); 
     // function logic goes here 
    } 

    dom.trace = $('#trace'); 
    var trace = function(value) { 
     dom.trace.append(value + '<br>')); 
    } 

    $(document).on('click','#Save',myObject.myFunction) 
})(jQuery, window); 

在這一點證明的概念,我已經扔在一起,我知道我可能做錯了12件事。

但這裏是我的問題點:

問:你如何命名功能,因此它可以自省?

+0

什麼是'introspected'? – jfriend00 2013-04-04 18:30:46

+0

爲什麼你不使用調試器?你可以通過'arguments.callee'獲得一個函數的名字,但是它將被逐步淘汰(不會在嚴格模式下工作,在未來的ECMAScript版本中可能不起作用)。 「 – bfavaretto 2013-04-04 18:33:02

+0

」將無法在嚴格模式下工作「。哦。這可能是我一直在對付我的頭。 – 2013-04-04 18:34:54

回答

0

http://www.learnjquery.org/tutorials/

function show_props(a,b,c,d,e) 
{ 
    var msg = "function name = " + arguments.callee.name + "\n"; 
    msg += "called from = " + show_props.caller.name + "\n"; 
    msg += "arguments.length = " + arguments.length + " argument(s) were passed.\n" 
    msg += "show_props.length (arity) = " + show_props.length + " argument(s) are defined total.\n"; 
    msg += "arguments = " + arguments + "\n"; 
    for (var i = 0; i < arguments.length; i++) 
     msg += "arguments[" + i + "] = " + arguments[i] + "\n"; 

    msg += "And arguments.callee.toString() is the function's literal body in string format = \n" + arguments.callee.toString() + "\n"; 

    alert(msg); 
} 

function parent() 
{ 
    show_props(1,2,3); 
} 

parent(); 

The result is shown below: 

function name = show_props 
called from = parent 
arguments.length = 3 argument(s) were passed. 
show_props.length (arity) = 5 argument(s) are defined total. 
arguments = [object Arguments] 
arguments[0] = 1 
arguments[1] = 2 
arguments[2] = 3 
And arguments.callee.toString() is the function's literal body in string format = 
function show_props(a,b,c,d,e) 
{ 
    var msg = "function name = " + arguments.callee.name + "\n"; 
    msg += "called from = " + show_props.caller.name + "\n"; 
    msg += "arguments.length = " + arguments.length + " argument(s) were passed.\n" 
    msg += "show_props.length (arity) = " + show_props.length + " argument(s) are defined total.\n"; 
    msg += "arguments = " + arguments + "\n"; 
    for (var i = 0; i < arguments.length; i++) 
     msg += "arguments[" + i + "] = " + arguments[i] + "\n"; 

    msg += "And arguments.callee.toString() is the function's literal body in string format = \n" + arguments.callee.toString() + "\n"; 

    alert("msg");