Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
How to call a class method from the button in js?

How to call a class method from the button? When the code is like below I get an 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 Respostas
Responde à pergunta

0

There are two ways of doing that. One is the static method and the second is initializing your class. Since you have a constructor setting some vars which are being used in add(), you need to initialize the class before calling its methods.

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 Relatório

0

You can use it if it is an static method, like this:

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`

if it is not static method you need to initialize object on whom that method will be called. For example:

class Account {
  #count;
  constructor(name, count) {
    this.name = name;
    this.#count = count;
  }  
  add() {
    return this.#count + 1;
  }
}

const newAcc = new Account("name", 0);

And then from your template you can do:

<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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda