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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Here's some Javascript which replaces adds console.log to every function in Javascript; Play with it on Regex101:
It's a 'quick and dirty hack' but I find it useful for debugging. If you have a lot of functions, beware because this will add a lot of code. Also, the RegEx is simple and might not work for more complex function names/declaration.
You can actually attach your own function to console.log for everything that loads.
Proxy Method to log Function calls
There is a new way using Proxy to achieve this functionality in JS. assume that we want to have a
console.log
whenever a function of a specific class is called:we can replace our class instantiation with a Proxy that overrides each property of this class. so:
check that this actually works in Codepen
Remember that using
Proxy
gives you a lot more functionality than to just logging console names.Also this method works in Node.js too.
Here's a way to augment all functions in the global namespace with the function of your choice:
One down side is that no functions created after calling
augment
will have the additional behavior.If you want more targeted logging, the following code will log function calls for a particular object. You can even modify Object prototypes so that all new instances get logging too. I used Object.getOwnPropertyNames instead of for...in, so it works with ECMAScript 6 classes, which don't have enumerable methods.