1
I don’t know what’s wrong with this code. Inside the function builder EvilCircle
, the this
works well, but in EvilCircle.prototype.draw
doesn’t work. It looks like it turns into Window.
function Shape(x, y, velX, velY, exists) {
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
this.exists = exists;
}
// EvilCircle
function EvilCircle(x, y, exists) {
Shape.call(this, x, y, 20, 20, exists);
this.color = 'white';
this.size = 10;
}
EvilCircle.prototype = Object.create(Shape.prototype);
EvilCircle.prototype.constructor = EvilCircle;
// Draw;
EvilCircle.prototype.draw = () => {
console.log(this);
};
As explained in the questions suggested above (in particular in this answer), the problem is that the
this
has different behavior in Arrow functions andfunction
's - which is one more reason not to go out using for no reason. I have seen a lot of people who think that Arrow functions are "the new way" (or worse, some think it’s the only way) to create functions, when in fact the use offunction
still proves necessary... The important thing is to know the difference, the implications, and evaluate when to use one or the other– hkotsubo
Aaaata. Thank you!
– Heitor Heitor Heitor