简体   繁体   中英

How do you name a function so that you can introspect it?

I'd like to write a routine that appends the name of a function to #trace whenever it's called:

;(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);

In this little proof-of-concept that I've thrown together, I know that I'm probably doing 12 things wrong.

But here's the point of my question:

Q: How do you name a function so that it can be introspected?

From 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM