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);
我可以将对象放入一个数组中并使用 splice 来清理它,但是没有数组有没有更好的方法?
谢谢你的提示:)
解决方案
据我所知,您不能在 JavaScript 中删除对象,因为其中有一个垃圾收集器会自动为您执行此操作。您可以通过将对象设置为null
或来标记要收集的对象undefined
。如果程序中没有对该对象的任何其他引用,GC 将删除它。
推荐阅读
- php - 推送通知不适用于 Android 与 php
- javascript - 将日期格式更改为字符串 d3 js
- ios - OverCurrentContext 防止方向改变
- javascript - Jquery鼠标事件在位置绝对内容中没有触发
- bash - Bash 通过多字符分隔符将多行字符串拆分为数组
- python - 如何将 grequests 响应与请求映射?
- gdb - 如何根据 gdb 是否附加到正在运行的进程,在 gdb 中执行“运行”或“继续”?
- ios - UInt8 数组未转换为字节字符串
- asp.net - 邮件发送失败。在 ASP.NET 中
- robotframework - 如何连接在机器人框架中具有一些代理设置作为先决条件的会话