满足条件后删除对象

时间:2019-04-16 18:51:26

标签: javascript

我想删除一个名为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);

我可以将对象放置到数组中并使用拼接来清理它,但是有没有数组的更好方法吗?
谢谢您的提示:)

3 个答案:

答案 0 :(得分:2)

据我所知,您无法在JavaScript中删除对象,因为其中有一个垃圾收集器会自动为您执行该操作。您只需将对象设置为nullundefined即可标记要收集的对象。如果您的程序中没有对该对象的任何其他引用,GC将删除它。

答案 1 :(得分:0)

我猜您实际上并不在乎删除对象本身(一旦不再访问该对象,Javascript的垃圾回收将自动处理该对象),而是希望停止渲染BossOne。

我可以通过添加一个hide函数来做到这一点,该函数应遵循以下原则:

ctx.clearRect(this.x, this.y, this.sizeX, this.sizeY);

然后添加一个标志以确保它不会被重新呈现。

答案 2 :(得分:0)

如果要在某个项目上使用delete,则必须将其附加到一个对象上,然后可以将其从该对象中删除。

在此示例中,我将类附加到窗口:

class A {}

window.a = new A

console.log(window.a)

delete window.a

console.log(window.a)

如果我们将值附加到letvar,则不会删除该值,但是,将值设置为undefined将允许垃圾收集器处理它,如您在本例中所见:

class A {}

let a = new A

console.log(a)

delete a

console.log(a)

// The garbage collector will take of it now
a = undefined

console.log(a)

相关问题