-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

George
  • 6,630
  • 2
  • 29
  • 36
Oliver Stott
  • 63
  • 1
  • 9
  • 1
    Well what exactly is the problem? What happens? Anything? Errors? – Pointy Jul 13 '18 at 12:28
  • 1
    `cnt` won't be defined in the `inc` function – George Jul 13 '18 at 12:29
  • 1
    Possible duplicate of [Self-references in object literal declarations](https://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – George Jul 13 '18 at 12:32
  • 2
    There are actually two issues. @George duplicate suggestion is right, it will solve your issue. But then you'll encounter another with the way you attach your eventListener because you're not attaching a function reference. Read the accepted answer here : [Javascript "addEventListener" Event Fires on Page Load](https://stackoverflow.com/questions/2373995/javascript-addeventlistener-event-fires-on-page-load) – Guillaume Georges Jul 13 '18 at 12:34
  • 1
    `counter.cnt++;` – epascarello Jul 13 '18 at 12:35

1 Answers1

1

There's no cnt variable defined inside the inc function. It(cnt) exists in the object counter not in the function inc. You could also solve this using the this reference. There are several articles in the web about it.

const counter = {
    cnt: 0,
    inc: function() {
        counter.cnt++;
        console.log(counter.cnt);
    }
};
Then008
  • 13
  • 1
  • 3
  • Change this line: `button.addEventListener('click', counter.inc(), false);` to: `button.addEventListener('click', counter.inc, false);` – Then008 Jul 13 '18 at 12:43
  • "You could also solve this using the this reference". Careful. A solution using `this` in the inc function will not work, because `this` will be a reference to the events target. Unless you add the event listener with `button.addEventListener('click', counter.inc.bind(counter), false)` – Guillaume Georges Jul 13 '18 at 12:53
  • @GuillaumeGeorges, yeah. – Then008 Jul 13 '18 at 12:58