每次点击都会增加JavaScript计数器?

Nav*_*HKA 0 javascript const javascript-objects

我需要更正此代码,以便在每次单击时增加它.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Clicker</title>
    <meta name="description" content="">
    <style></style>
</head>
<body>
    <button>Click!</button>

<script>
    const counter = {
        cnt: 0,

        inc: function() {
            cnt++;
            console.log(cnt);
        }
    };

    const button = document.getElementsByTagName('button')[0];
    button.addEventListener('click', counter.inc, false);

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我现在的解决方案工作正常,但不确定它背后的概念是什么,解决方案是:

inc: function() {
    counter.cnt++;
    console.log(counter.cnt);
}
Run Code Online (Sandbox Code Playgroud)

Raj*_*amy 8

这只是个scoping问题,

 //Right approach would be,

 const counter = {
  cnt: 0,
  inc: function() {
   this.cnt++;
   console.log(this.cnt);
  }
 };
Run Code Online (Sandbox Code Playgroud)

您的错误代码将查找cnt在当前作用域中声明的变量并遍历到全局变量.如果找不到引用,它将抛出错误.

由于您inc要将事件侦听器作为事件侦听器传递,因此必须为其绑定范围,否则,该this函数的内部将指向触发事件的元素.在这种情况下,元素将是a button.

button.addEventListener('click', counter.inc.bind(counter), false);
Run Code Online (Sandbox Code Playgroud)

或者最可读的方法是,

button.addEventListener('click', function() { 
 counter.inc() 
}, false);
Run Code Online (Sandbox Code Playgroud)

避免的另一个原因.bind是,如果将上下文绑定到函数使用,则一次.bind.之后你不能覆盖它的上下文.即使使用.call/.apply