Suppose I have a class like this:
let initPack = { player: [] };
let Player = function(param) {
let self = {
id: param.id,
x: param.x,
y: param.y
}
self.update = function() {
self.x += 1;
self.y += 1;
}
self.getInitPack = function() {
return {
id: self.id,
x: self.x,
y: self.y
}
}
Player.list[self.id] = self;
initPack.player.push(self.getInitPack());
return self;
}
Player.list = {};
If I want to rewrite this to ES6 classes and put it into a separate file in node.js, such as:
module.exports = class Player {
constructor(param) {
this.id = param.id;
this.x = param.x;
this.y = param.y;
}
update() {
this.x += 1;
this.y += 1;
}
getInitPack() {
return {
id: self.id,
x: this.x,
y: this.y
}
}
}
How can I rewrite the rest of the class to make it work like the previous one? There are some static members and use of external variables in the original file. But I am not sure how to do that correctly in ES6.
initPack? Do you want it also to be a "static field" ofPlayer?initPackwas not a static member but a global variable which was used in somewhere else in the project. Each time I instantiate aPlayerobject it will be pushed into the static list and its initial data will be pushed intoinitPack's player array. Do I have to use aninitmethod in the class? That seems a bit odd because now I have to init the class before I can use static members.Player.list[self.id]and thepushstatement in the constructor. Just replaceselfwiththis.initfunction is a workaround, but notice that it gets called and deleted from the class immediately after the class declaration, so you don't have to worry about initializing the static members later.