0

I have an es6 class 'Snake' in snake.js

I have an index.js

index.js instantiates a 'Snake'

index.js calls snake.move(dir)

I get an error this.isProperDir is not a function

snake.js

    isProperDir(dir) {
        dir = dir.toLowerCase();
        var arr = ['left', 'up', 'down', 'right'];
        return arr.includes(dir);
    }

    move(dir) {
        console.log('a2: ' + this);
        console.log('d: ' + this.isProperDir(dir));
    }

index.js

window.setInterval(snake.move, 1000);

This gets printed to console:

a2: [object Window]

Uncaught TypeError: this.isProperDir is not a function

I just want to call that function inside my es6 class, I figure writing this would refer to the function inside that class, but it seems to instead throw errors.

James Andrew
  • 197
  • 1
  • 4
  • 16
  • 1
    please add the full code that can be run, or attach a fiddle or something, it's not clear enough – Raghvendra Kumar Apr 04 '19 at 11:38
  • Uploaded some code to jsfiddle, its not working for some reason https://jsfiddle.net/g403e8j6/3/ – James Andrew Apr 04 '19 at 11:49
  • You did notice the link to the duplicate…? – deceze Apr 04 '19 at 11:56
  • I didnt understand it well, I come from a Java background, where using 'this' in a class object refers to the object itself. Are you able to help me understand my issue? The jsfiddle is there. I did look at that solution though before I posted but I didnt quite understand it – James Andrew Apr 04 '19 at 12:03
  • In a nutshell: `this` is set at *calltime*, and depends on how you *call* the function. When calling `a.b()`, `this` inside `b` is `a`. When calling `b()`, there is no `this` inside `b` (well, it becomes `window`). `setInterval` works something like `function setInterval(fun) { fun(); }`, hence no `this` inside `fun`. Now read the duplicate again. – deceze Apr 04 '19 at 12:16
  • Ohh alright, is there any specific reason for this, any real advantages this has over the other 'Java' approach? Just wondering why this would even be a thing? – James Andrew Apr 04 '19 at 12:21
  • ‍♂️ Ask [Brendan](https://en.wikipedia.org/wiki/Brendan_Eich)… – deceze Apr 04 '19 at 12:23
  • Wait Im still confused o.o if you have a look at my code you can maybe see why. in my `window.setInterval(snake.move, 1000)`, would mean that inside `move()` in the snake class, `this` would refer to the `snake` variable. – James Andrew Apr 04 '19 at 12:37

0 Answers0