I built a hook for the toString
method using ES6 Proxy. While debugging some issues I noticed the console.log
of handler getting called for no reason.
class Hook {
constructor(object) {
this.object = object;
}
toStringProperty() {
const handler = {
apply: (target, thisArg, args) => {
console.log(target, thisArg, args);
if (thisArg === Function.prototype.toString) {
return 'function toString() { [native code] }'
}
if (thisArg === this.object) {
return "Hooked String"
}
return target.apply(thisArg, args)
}
}
Function.prototype.toString = new Proxy(Function.prototype.toString, handler)
}
}
let hook = new Hook(HTMLAudioElement);
hook.toStringProperty()
HTMLAudioElement.toString();
I spent a lot of time trying to find what causes this recursion but I'm afraid that I can't find anything.
Note: this behavior also happens after typing HTMLAudioElement
or ooo
in console and of course you have to do this after running the above code. My browser is Chrome. I tested with Devtools Console.