2013-04-04 80 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");