+ 1
Why does my canvas don't draw my rect ?
Can't understand why it doesn't want to draw my snake... Thanks you <3 https://code.sololearn.com/W1KrHNDRYNA5/?ref=app
5 Respuestas
+ 2
The reason is because in JavaScript the keyword ‘this’ referes to the current object it is referenced in. For instance
var move = function() {
this.x; //references the anonymous function declared here
}
but what you can do to avoid this is to declare a variable outside of the fucntion that is assigned the value of ‘this’ for instance:
var self = this;
move = function() {
self.x; // is not refering to the object outside of the anonymous function;
}
Another way to avoid this would be to use the ES6 fat arrow function declaration, like:
var self = this;
move = () => {
this.x === self.x; //true
// the fat arrow declaration doesn’t overload the ‘this’ keyword
// so is still a reference to the outmost object.
}
in your Snake class if you define a variable like such
var self = this;
then use that variable instead of the ‘this’ keyword inside of your functions it will work fine.
Edit: correct my arrow function syntax
+ 4
line 37 and 38 draw and move are methods of Class Snake so you need snake.draw() < parenthisis this will show rect
0
Thank you so much <3
But if you don't mind to explain me, I don't really understand what does it changes to create a variable self...
0
Here I wrote you a bit of example code using your Snake object and it’s draw methods as examples.
https://code.sololearn.com/Wqy0DSM93x5E/?ref=app
0
the setIntetval method takes a function references as the first argument. Adding the parentheses will give the return value of those functions (which in this cause would be null as nothing is returned from the function.)