Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding console.log to every function automatically

Is there a way to make any function output a console.log statement when it's called by registering a global hook somewhere (that is, without modifying the actual function itself) or via some other means?

like image 319
JRL Avatar asked Feb 17 '11 19:02

JRL


People also ask

Can you put console log in a function?

log() with Examples. The console. log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.

Is console log () added to execution stack?

It's a function call. It goes to the call stack.

How do you wrap a console log?

Type it and press Ctrl+Alt+W + W . Another way to console. log your variables is to simply place your mouse cursor on them and then wrap them on the line below with Ctrl+Alt+W + Down or the line above with Ctrl+Alt+W + Up .

Is console log synchronous or asynchronous?

"So what?" you probably asked? - This is important part, because console. log() is asynchronous. All asynchronous functions come to Event Table in terms of Event Loop.


1 Answers

Here's a way to augment all functions in the global namespace with the function of your choice:

function augment(withFn) {     var name, fn;     for (name in window) {         fn = window[name];         if (typeof fn === 'function') {             window[name] = (function(name, fn) {                 var args = arguments;                 return function() {                     withFn.apply(this, args);                     return fn.apply(this, arguments);                  }             })(name, fn);         }     } }  augment(function(name, fn) {     console.log("calling " + name); }); 

One down side is that no functions created after calling augment will have the additional behavior.

like image 183
Wayne Avatar answered Nov 02 '22 23:11

Wayne