I tried to proxy Function.prototype.
I created a new Proxy and rewrote the toString method, however console.log('cas') doesn't work, why?
Function.prototype = new Proxy(Function.prototype, {
get: function(target, property, receiver) {},
set: function(target, property, value, receiver) {
console.log('cas')
}
})
Function.prototype._toString = Function.prototype.toString;
Function.prototype.toString = function() {
console.log('bb')
return this._toString()
}
Ok, we cannot overwrite
Function.prototypebut we can set the prototype ofFunction.prototype(an evil professor's laugh here):UPDATE
The author noticed that the solution doesn't work in node.js.
The reason that
console.logis environment specific plus overridingFunction.prototypemeans that if you call a function that callsapply,call,bindyou go into recursion and stack overflow (RangeError: Maximum call stack size exceeded).So the code should be adjusted to your specific execution environment. On my node.js version 18 these tweaks helped. Moreover I had to override
console.logsince the output was empty. Again, environment-specific (seems another investigation...). During debuggingconsole.logworked but required to avoid gettinglistenerproperty.So my conclusion: it works if you care about recursion with specific methods on your platform AND I will be working on an environment-independent solution, the plan is to register function calls and avoid recursion by checking whether there's already a function call that leads to the stack overflow.