3

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.

jeffbRTC
  • 1,941
  • 10
  • 29

1 Answers1

3

Inside the handler, you call console.log(target, thisArg, args); where target and thisArg are functions. The devtools console appears to use .toString() to get the name of the function to display it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375