首页 > 解决方案 > 满足条件后删除对象

问题描述

我想删除一个名为 bossOne 的对象,它是在我的类 BossOne 的基础上制作的。

应该这样做:

let bossOne;
bossOne = new BossOne();

if(true) {
delete bossOne;
}

我的课:

class BossOne {
    constructor() {
        this.x = canvas.width/2 - canvas.width/6;
        this.y = 200;
        this.sizeX = canvas.width/3;
        this.sizeY = canvas.width/14;
        this.speed = 3;
    }

    show() {
        ctx.fillStyle = "#FFF";
        ctx.fillRect(this.x, this.y, this.sizeX, this.sizeY);
    }

    changeDirection() {
        this.speed *= -1;
    }

    move() {
        this.x += this.speed;
    }
}

主要代码:

let bossOne;
bossOne = new BossOne();

function draw() {
    requestAnimationFrame(draw);
    bossOne.show();
    bossOne.move();
}

requestAnimationFrame(draw);

我可以将对象放入一个数组中并使用 splice 来清理它,但是没有数组有没有更好的方法?
谢谢你的提示:)

标签: javascript

解决方案


据我所知,您不能在 JavaScript 中删除对象,因为其中有一个垃圾收集器会自动为您执行此操作。您可以通过将对象设置为null或来标记要收集的对象undefined。如果程序中没有对该对象的任何其他引用,GC 将删除它。


推荐阅读