Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda