【发布时间】:2019-08-02 21:55:17
【问题描述】:
我正在制作盗版 agar.io。每次创建 Blob(游戏中所有循环实体的父类,包括玩家和食物)时,都会在 Blob 类的静态数组中存储一个引用。我想为扩展 Blob 类的 Food 类做同样的事情(创建一个类的所有实例的静态数组)。
我已经尝试过:在所有三个类的构造函数中,对象被推送到.all 静态数组,因此所有实例都可以通过Blob.all 或Food.all 访问。要在推送this 之前初始化静态变量,我意识到如果等于null,我需要将.all 设置为一个空数组。
const Blob = class extends Point {
constructor(x = 0, y = 0, radius = 5, color = `rgb(0, 0, 0)`) {
super(x, y)
this.radius = radius
this.color = color
this.deleted = false
Blob.all = Blob.all || []
Blob.all.push(this)
}
static draw(ctx) {
Blob.all.forEach(blob => blob.draw(ctx))
}
// ...
delete() {
this.deleted = true
Blob.all.filter(blob => blob !== this)
}
}
const Food = class extends Blob {
constructor(x = 0, y = 0) {
super(x, y, 5, `rgb(255, 150, 120)`)
Food.all = Food.all || []
Food.all.push(this)
}
static draw(ctx) {
Food.all.forEach(food => food.draw(ctx))
}
// ...
delete() {
super.delete()
Food.all.filter(food => food !== this)
}
}
const Player = class extends Blob {
constructor(x = 0, y = 0, color = `rgb(100, 100, 100)`) {
super(x, y, 20, color)
Player.all = Player.all || []
Player.all.push(this)
}
static draw(ctx) {
Player.all.forEach(player => player.draw(ctx))
}
// ...
delete() {
super.delete()
Player.all.filter(player => player !== this)
}
}
// ...
// oversimplification of how I'm initializing and looping my game
gameInit = _ => {
// creates 100 new instances of Food
for (let i = 0; i < 100; i++) new Food(randX, randY)
// creates 1 new instance of a player
let player = new Player()
}
drawLoop = _ => {
Food.draw(ctx)
Player.draw(ctx)
}
在gameInit() 之后,我希望Player.all 是一个包含 1 个实例(1 个 Player 对象)的数组。
我还希望Food.all 是一个包含 100 个实例(100 个 Food 对象)的数组。
我还希望Blob.all 是一个包含 101 个实例(100 个 Food 对象,1 个 Player 对象)的数组。
原来,Player.all、Food.all、Blob.all 面积都相等!它们都共享相同的静态变量。不仅我不希望它们都共享同一个变量,而且该数组中有 202 个对象,因为在创建 Food 时,它会被推送到静态变量两次。
如何获得预期的结果?
【问题讨论】:
标签: javascript es6-class