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

182
Views
¿Cómo llamar a un método de clase desde el botón en js?

¿Cómo llamar a un método de clase desde el botón? Cuando el código es como el siguiente, aparece un error:

 Uncaught TypeError: Account.add is not a function at HTMLButtonElement.onclick 

 class Account { #count; constructor(name, count) { this.name = name; this.#count = count; } add() { return this.#count + 1; } }
 <h1>Something about ...</h1> <div> <h1 id='sth'> Something </h1> </div> <button type="button" onclick="Account.add()">Click me</button>

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

0

Hay dos formas de hacerlo. Uno es el método estático y el segundo es inicializar su clase. Dado que tiene un constructor configurando algunos vars que se utilizan en add(), debe inicializar la clase antes de llamar a sus métodos.

 class Account { #count; constructor(name, count) { this.name = name; this.#count = count; } add() { return this.#count + 1; } } const account = new Account(); // <----- Initialize class
 <h1>Something about ...</h1> <div> <h1 id='sth'> Something </h1> </div> <button type="button" onclick="account.add()">Click me</button>

about 4 years ago · Juan Pablo Isaza Report

0

Puedes usarlo si es un método estático, como este:

 class Account { #count; constructor(name, count) { this.name = name; this.#count = count; } static add() { return this.#count + 1; } } // but now you will get different error since static methods have different `this`

si no es un método estático, debe inicializar el objeto en el que se llamará a ese método. Por ejemplo:

 class Account { #count; constructor(name, count) { this.name = name; this.#count = count; } add() { return this.#count + 1; } } const newAcc = new Account("name", 0);

Y luego desde tu plantilla puedes hacer:

 <body> <h1>Something about ...</h1> <div> <h1 id='sth'> Something </h1> </div> <button type="button" onclick="acc.add()">Click me</button> </body>

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!