+ 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 RĂ©ponses
+ 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.)