Javascript OOP 计数值在 class 之外不起作用

Javascript OOP counting value doesn't work outside class

我有这个计数变量。每次我按下某个按钮时,count 变量计数为 1,默认情况下它从 0 开始。这有效,但是当我尝试在 class 之外使用它时,它不记得该值。我知道这应该行不通,但我不知道该怎么做才好

    class navigation{

        constructor() {
            this.count = 0;
        }

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

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

我希望值随处可用,如下所示:

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

但是从那里的日志中我得到了默认值 0。我该怎么做才正确?

您每次单击时都在实例化一个新导航,您想将其移到外面:

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>

编辑:添加了第二个按钮以显示如何添加独立侦听器

如果您希望 count 成为每个 Navigation 实例上的 public 属性,那么您需要从对象实例外部正确引用它,使用nav.count.

请注意,在下文中,每个 Navigation 实例如何维护自己的 count public 实例变量。

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>

或者,如果您在 class 之外创建一个 block-scoped 变量,它将被当前块中的代码共享。

请注意,在下文中,block-scoped 变量 count 是如何被我们创建的 Navigation 的每个实例共享的。

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>