BaoLuo Posted July 23, 2022 Share Posted July 23, 2022 Hello everyone! Can anybody explain me why this variant of binding works document.querySelector('.burger').addEventListener('click', _ => { burgerLine.play() }) and this one document.querySelector('.burger').addEventListener('click', burgerLine.play) causes the following error Quote gsap.min.js:10 Uncaught TypeError: this.seek is not a function at HTMLButtonElement.play (gsap.min.js:10:19754) Link to comment Share on other sites More sharing options...
GreenSock Posted July 23, 2022 Share Posted July 23, 2022 Yeah, that's because of how scope works in JavaScript. Consider this class: class Thing { constructor() { this._playing = false; } play() { this._playing = true; } } And now let's do this: let a = new Thing(); let b = new Thing(); We've got two "Thing" instances. Now let's do: document.querySelector("#id").addEventListener("click", a.play); Technically you're only passing the function ITSELF as the handler. That function definition is shared by ALL instances of "Thing" (a and b in our case). Think of it like a template. When you call a.play(), for example, it calls that method with a very particular scope - "a" is the scope, so "this" inside the function refers to that one particular instance. If you call b.play(), "b" is the scope, so "this" inside the function refers to the b instance. That all happens because you're directly calling the method on the instance, like a.play() and b.play(). But when you set up an event handler and you only pass in the function itself, you lose the scope. So when it calls that method on the event, the scope would be the clicked element itself! So "this" inside play() doesn't refer to "a" at all - it refers to the clicked element. So yeah, don't do that It's a JavaScript thing, not a GSAP thing. Link to comment Share on other sites More sharing options...
BaoLuo Posted July 25, 2022 Author Share Posted July 25, 2022 Thank you very much for such a detailed answer! Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now