Search code examples
javascriptfunctionvariablescounting

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?


Solution

  • 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