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

179
Visualizações
Javascript OOP counting value doesn't work outside class

I have this count variable. Each time I press a certrain button the count variable counts one and it starts with 0 as a default. This works, but when I try using it outside the class it doesn't remember the value. I know this shouldn't work, but I have no idea how to do it right

    class navigation{

        constructor() {
            this.count = 0;
        }

        NextBtn(){
            this.count++
            console.log(this.count);
        }

        ResultBtn(){
            console.log(this.count)
        }
    }

I want the value to be available everywhere like here:

 let nav = new navigation();
 const count = nav.count;
 btn.addEventListener("click", function (btn) {
     nav.NextBtn();
     console.log(count)
})

But out of there logs I get the default value which is 0. How do I do this right?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you want count to be a public property on each Navigation instance, then you need to refer to it correctly from outside the object instance, using nav.count.

Note how, in the following, each Navigation instance maintains its own count public instance variable.

class Navigation {
  constructor() {
    this.count = 0
  }

  count = 0

  next() {
    this.count++
    console.log("From inside `next`: ", this.count)
  }
}

let nav1 = new Navigation()
let btn1 = document.getElementById("btn1")

let nav2 = new Navigation()
let btn2 = document.getElementById("btn2")

btn1.addEventListener("click", function (btn) {
  nav1.next()
  console.log("From inside btn1 event listener: ", nav1.count)
})

btn2.addEventListener("click", function (btn) {
  nav2.next()
  console.log("From inside btn2 event listener: ", nav2.count)
})
<button id="btn1">Click me 1</button>
<button id="btn2">Click me 2</button>

Alternatively, if you create a block-scoped variable outside the class, it will be shared by the code in the current block.

Note how, in the following, the block-scoped variable count is shared by every instance of Navigation we create.

let count = 0

class Navigation {
  next() {
    count++
    console.log("From inside `next`: ", count)
  }
}

let nav1 = new Navigation()
let btn1 = document.getElementById("btn1")

let nav2 = new Navigation()
let btn2 = document.getElementById("btn2")

btn1.addEventListener("click", function () {
  nav1.next()
  console.log("From inside btn1 event listener: ", count)
})

btn2.addEventListener("click", function () {
  nav2.next()
  console.log("From inside btn2 event listener: ", count)
})
<button id="btn1">Click me 1</button>
<button id="btn2">Click me 2</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

You are instantiating a new navigation every time you click, you want to move that outside:

class navigation{

    constructor() {
        this.count = 0;
    }

    NextBtn(){
        this.count++
        console.log(this.count);
    }

    ResultBtn(){
        console.log(this.count)
    }
}

const next = document.getElementById("next");
const result = document.getElementById("result");

const nav = new navigation();

next.addEventListener("click", function (e) {
    nav.NextBtn();
})

result.addEventListener("click", function (e) {
    nav.ResultBtn();
})
    <button id="next">Next</button>
    <button id="result">Result</button>

EDIT: Added a second button to show how to add independent listeners

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