0

The following javascript module add a simple div into html file. When I called board.drawIn(), everything works well. But when I called board.initIn(), I got,

gomoku.js:3 Uncaught TypeError: Cannot set properties of undefined (setting 'board')

I'm quite confused because initIn() function actually does nothing but call drawIn() directally. Anyone can help?

const board = (() => {
    function drawIn(container) {
        this.board = document.createElement('div');
        this.board.classList.add('gomokuBoard');
        container.appendChild(this.board);
    }

    function initIn(container) {
        drawIn(container);
    }

    return { drawIn, initIn };

})();

const gomoku = (() => {
    function initIn(container) {
        //board.drawIn(container);    /* this works */
        board.initIn(container);      /* doesn't work */
    }

    return { initIn };
})();

gomoku.initIn(document.querySelector('body'));
.gomokuBoard {
    width: 100px;
    height: 100px;
    border: 1px solid black;
}
shen
  • 933
  • 10
  • 19
  • it's because `this` is undefined – Bravo Mar 08 '22 at 06:03
  • 1
    `drawIn(container);` is a call expression statement without a base reference. Why do you expect `this` to be `board` inside `drawIn` when called like this? There’s no connection between the two. – Sebastian Simon Mar 08 '22 at 06:05
  • I called `board.initIn(container)`, so `this` should be `board` object? – shen Mar 08 '22 at 06:06
  • No, that's not correct, only works if you instantiate an instance using `new` – Bravo Mar 08 '22 at 06:07
  • 1
    @shen `this` is `board` _inside `initIn` only_. You don’t use `this` there. Then you go on to call `drawIn(container);`; the `this` reference is not used here, so it’s lost. If you want to use `board.initIn(container)`, then the `drawIn` call should look like `drawIn.call(this);`, for example. – Sebastian Simon Mar 08 '22 at 06:08
  • So I should call `this.drawIn(container);`? I tried, it works. – shen Mar 08 '22 at 06:09
  • 1
    @shen See my edited comment. `this.drawIn` may work here, but it won’t work in similar situations. – Sebastian Simon Mar 08 '22 at 06:10
  • Ok I understand now, thanks a lot Bravo and Sebastian Simon. `this` in Javascript almost kill me since I was a Java programmer... – shen Mar 08 '22 at 06:13

0 Answers0