Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
"x no es una función" en js cuando se usa la clase

Soy nuevo en JS y especialmente en clase en JS. No entiendo completamente cómo funcionan las clases. Por favor ayúdame en la siguiente pregunta. Esta es una página simple con un botón. Quiero que ejecute una función (doThis()) después de hacer clic en el botón. Pero da un error diciendo que la función no está definida.

 class Test { constructor() { this.button = document.getElementById("but1"); this.button.addEventListener("click", this.butClick); } butClick() { console.log("clicked"); this.doThis(); } doThis(){ console.log("Inside doThis") } } t1 = new Test();
 <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <button id="but1">Click me</button> <script src="test.js"></script> </body> </html>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

this.button.addEventListener("click", this.butClick); debería ser this.button.addEventListener("click", this.butClick.bind(this)); .

Sin bind(this) , this inside butClick es solo el elemento del button , no la class Test .

about 4 years ago · Juan Pablo Isaza Report

0

 class Test { constructor() { } butClick() { console.log("clicked"); this.doThis(); } doThis(){ console.log("Inside doThis") } } t1 = new Test(); const button = document.getElementById("but1") button.addEventListener('click', event => { event.preventDefault() // Call doThis method on t1, the instance... t1.doThis() })
 <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <button id="but1">Click me</button> <script src="test.js"></script> </body> </html>

He escrito un artículo breve y útil sobre el uso de clases en JS, debería ayudar, vaya al artículo aquí .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!