删除:如何确保没有内存泄漏?

时间:2016-06-09 10:09:38

标签: javascript three.js

这是我的代码,我想知道删除是否足以破坏对象并且没有内存泄漏:

class Shoot extends MovableObject{
constructor(){
    super();
    this.speed = 2;
    this.geometry = new THREE.CircleGeometry(0.5);
    this.material = new THREE.MeshBasicMaterial({ color: 0xffffff });
    this.mesh = new THREE.Mesh(this.geometry, this.material);
}

setRotation(rotation){
    this.mesh.rotation.set(rotation.x, rotation.y, rotation.z);
}

setPosition(position){
    this.mesh.position.set(position.x, position.y, position.z);
}

}

后来我有了这个功能,listShoot是我拍摄实例的唯一地方:

var position;
listShoot.forEach(function(shoot, i, list){
    position = shoot.getMesh().getWorldPosition();
    if(/*i want to destroy my shoot*/){
        list.splice(i, 1);
        scene.remove(shoot.getMesh()); // This is ThreeJS
        delete shoot;
        console.log("shoot destroyed");
    }
});

2 个答案:

答案 0 :(得分:0)

虽然我无法给你一个完整的答案,但我知道你不能删除属于闭包的变量。

var myfunc = function(a, b, c) {
  console.log(a,b,c);
  delete b;
  console.log(a,b,c);
}; 

myfunc(1,2,3);

以上代码将输出以下内容:

1 2 3
1 2 3

关于闭包have a look at this related question中的垃圾收集。

您始终可以将undefined分配给变量。

var myfunc = function(a, b, c) {
  console.log(a,b,c);
  b = undefined;
  console.log(a,b,c);
}; 

myfunc(1,2,3);

哪个输出:

1 2 3
1 undefined 3

答案 1 :(得分:0)

我认为您应该将shoot变量置零,以丢失链接。 像这样:

shoot = null;
console.log("shoot destroyed");