Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get javascript object method name?

Tags:

javascript

I'm currently building a bigger object and need to get faster and more specific with debugging/inspecting values/results/returns.

Now I thought about the following:

var myObject = {
    whatever: null,
    whereever: null,
    debug: false,

    someFunction: function( arg ) {
        // General - would output *all* logs for all object functions.
        // if ( true === myObject.debug )
        //  console.log( 'FunctionNameHere', arg );

        // More specific - would output *only* the log for the currently targeted function
        if ( 'FunctionName' === myObject.debug )
            console.log( 'FunctionNameHere', arg );
    },
};

This would allow me to simply define the object var debug as one function name and only log this part.

The only problem is: How would I obtain the FunctionName/someFunction?

Sidenotes:

  • console.log( arguments.callee ); gives me the whole function source.
  • console.log( arguments.callee.name ); returns empty.
  • console.log( arguments.callee.toString() ); returns empty
  • console.log( arguments.caller ); returns undefined

If I take a look into the log of the whole object, I see prototype.name="Empty" and such. So no chance to get it directly out of the object.

Thanks!

like image 784
kaiser Avatar asked Jun 09 '26 04:06

kaiser


1 Answers

If you want to log every function if debug is true and if debug is set to the name of function, then log only that function you don't have to hardcode this into every single function of yours.

What you can do is dynamically rewrite the function. It is bit of a magic, but it is lot more flexible and you don't have to change anything when you add more functions or change their names.

HERE is the working code.

for (var key in myObject) {
  // if the keys belongs to object and it is a function
  if (myObject.hasOwnProperty(key) && (typeof myObject[key] === 'function')) {
    // overwrite this function
    myObject[key] = (function() {
      // save the previous function
      var functionName = key, functionCode = myObject[functionName];
      // return new function that will write log message and run the saved function
      return function() {
        if (myObject.debug === true || myObject.debug === functionName) {
          console.log('I am function ' + functionName, ' with arguments: ', arguments);
        }
        functionCode(arguments);
      };
    })();
  }
}
like image 73
kubetz Avatar answered Jun 10 '26 20:06

kubetz