0

Let me say there is an audio object named myAudio which is playing music now on. I wanted to make a button element which pauses the music when an user push it. First, I implemented like this:

const btn = document.createElement("div");
btn.addEventListener("click",myAudio.pause); // caught an illegal invocation error.

I embed the pause method directly in the second argument of the addEventListener. However, the browser returned illegal invocation error even if the pause method is surely defined in Audio object of HTML5.

Secondly, I tried to write pause method using arrow funciton:

const btn = document.createElement("div");
btn.addEventListener("click",() => myAudio.pause()); // it worked 

And it worked.

I don't get why the first way is impossible. Is it just my misunderstanding of a syntax of JavaScript or the problem that is specific of audio object?

addition

I'm sorry I could not understand what of the suggested question is related with this question. The suggested question is about this keyword but I could not find this in my snippet above. Is it that this keyword is used inside the pause method?

somia
  • 193
  • 10
  • 3
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+method+loses+this+context+when+passed+as+parameter) of [Losing "this" context in JavaScript when passing around members](https://stackoverflow.com/q/30486345/4642212). You can still use `myAudio.pause.bind(myAudio)`. – Sebastian Simon Mar 16 '21 at 10:12
  • Thank you. Do you mean `this` keyword is used inside the pause method and we need to explicitly bind it with `myAudio`? – somia Mar 16 '21 at 10:37
  • 1
    Yes, implicitly. `Audio.prototype.pause` is implemented by the host environment, so there isn’t necessarily a literal `this` keyword; the important thing is that a _`this` context_ is used in that method. – Sebastian Simon Mar 16 '21 at 10:40
  • I got it. Thank you. – somia Mar 16 '21 at 15:50

0 Answers0