So, I'm going through eloquent javascript's platform game and in this class, why are we storing size
property in the prototype?
The description says:
The size property is the same for all instances of Player, so we store it on the prototype rather than on the instances themselves. We could have used a getter like type, but that would create and return a new Vec object every time the property is read, which would be wasteful. (Strings, being immutable, don’t have to be re-created every time they are evaluated.)
But I couldn't understand that. Help me out!
class Player {
constructor(pos, speed) {
this.pos = pos;
this.speed = speed;
}
get type() { return "player"; }
static create(pos) {
return new Player(pos.plus(new Vec(0, -0.5)),
new Vec(0, 0));
}
}
Player.prototype.size = new Vec(0.8, 1.5);
Also, if anyone has completed the game, can anyone tell me how the x and y coordinates are taken here in new Vec(0.8, 1.5)
, new Vec(0, -0.5)
and new Vec(0, 0)
. I' m having hard time understand it. Thanks!
Storing on prototype is similar to static properties in other languages (eg. Java) That means there is only single Vec instance shared across all Player instances.
When you access any player's property, iJavaScript first looking for regular property on player instances, if not found looking on class prototype, then parent class prototype and so on.
In this case, it's jut optimization. Instead of creating Vec instance for each player there exist only single on in a memory. In other words you can look at as constant.