-3

I'm trying to work out how to solve this JavaScript code challenge. I'm really struggling and would like some advice please?

I'm trying to improve on my ability to debug and I struggled with this one.

<!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>

But I get the error

Uncaught ReferenceError: cnt is not defined on line 19

4

1 回答 1

1

cntinc 函数内部没有定义变量。It( cnt) 存在于对象counter中而不存在于函数中inc。您也可以使用this参考解决此问题。网上有几篇关于它的文章。

const counter = {
    cnt: 0,
    inc: function() {
        counter.cnt++;
        console.log(counter.cnt);
    }
};
于 2018-07-13T12:34:28.003 回答