0

I wrote a proxy of HTMLAudioElement. When I call play() method via the proxy.

const proxy = new Proxy( audioPlayer, {
  get(target: typeof audioPlayer , prop, receiver) { 
    return Reflect.get(target, prop, receiver);
  }
});
proxy.play();

I got a Error:

TypeError: Failed to execute 'play' on 'HTMLMediaElement': Illegal invocation

As far as I know, it is because that the play function is not bind to target. However, Shouldn't the prop receiver do the binding for us? Or something wrong in my code?

Then, I have to change my code as below, it looks weired, but works.

   const proxy = new Proxy( audioPlayer, {
        get(target: typeof audioPlayer , prop, receiver) { 
            if(prop=='play'){
                return target.play.bind(target)
            }else if(prop=='pause'){
                return target.pause.bind(target)
            }
            return Reflect.get(target, prop, receiver);
        }
   });
   proxy.play();
sean qu
  • 11
  • 3
  • 1
    No, `receiver` has nothing to do with auto-binding. It's useful for getters and setters, especially for inherited ones. Also in your example `receiver === proxy`, binding to that wouldn't do any good. – Bergi Apr 25 '22 at 18:05
  • Why are you using a proxy here at all? – Bergi Apr 25 '22 at 18:05
  • See [here](https://stackoverflow.com/a/45966614/1048572) for why this error happens – Bergi Apr 25 '22 at 18:06
  • 1
    I deleted some code for a clearer view in my example. but I got you idea, its solve my problem . thx – sean qu Apr 25 '22 at 18:28

0 Answers0