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 emptyconsole.log( arguments.caller ); returns undefinedIf 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!
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);
};
})();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With