+ 3

Problem with JS Class and Event Listener

I have a JS object which contains a div element. The "log" method of that object is called when the div is clicked, but it fails to read the value of the property "num". I need to know why it's happening and how to solve it. https://sololearn.com/compiler-playground/WHM9TyFgir33/?ref=app

20th Jan 2024, 1:15 PM
Nor'wester 🌪️ 🇧🇩 (INACTIVE)
Nor'wester 🌪️ 🇧🇩 (INACTIVE) - avatar
6 Answers
+ 3
You need to bind the log to the instance by changing this.log.bind(this) in the 11 line.
20th Jan 2024, 2:24 PM
Fandi Presly Simamora
Fandi Presly Simamora - avatar
+ 5
Hi friend 😃👋🏻 Fandi Presly Simamora is true you should use the bind function; why!? That's because when the click is triggered, the "log" method is called separately, so "this" is lost! It is the same as you use "log" function out of your class, so you don't have "num". That's why it prints "undefined". By using the "bind" function, you are reminding your function that when the click event is triggered, you belong to "clickableDiv" class. Now it works!
20th Jan 2024, 2:50 PM
🇮🇱 Radin Masiha 🇮🇱
🇮🇱 Radin Masiha 🇮🇱 - avatar
+ 5
you can also do this this.div.addEventListener( "click", ()=>this.log() );
20th Jan 2024, 10:11 PM
Bob_Li
Bob_Li - avatar
+ 1
Thanks! Now, why does it work?
20th Jan 2024, 2:41 PM
Nor'wester 🌪️ 🇧🇩 (INACTIVE)
Nor'wester 🌪️ 🇧🇩 (INACTIVE) - avatar
20th Jan 2024, 6:22 PM
Nor'wester 🌪️ 🇧🇩 (INACTIVE)
Nor'wester 🌪️ 🇧🇩 (INACTIVE) - avatar
+ 1
Yeah, that works, too
22nd Jan 2024, 12:28 AM
Nor'wester 🌪️ 🇧🇩 (INACTIVE)
Nor'wester 🌪️ 🇧🇩 (INACTIVE) - avatar