将实例设置为空

时间:2017-08-14 20:32:24

标签: javascript garbage-collection garbage

所以我通过JavaScript Memory Management和其他一些文章阅读,我知道有一些垃圾收集守护进程在某个时间间隔内运行,并自动神奇地清理。

我遇到的问题是即使我将对象实例设置为null并在设置timeOut后运行null检查null,但实例仍然存在。

使用一个简单的例子来解决这个问题:



class Animal{
	constructor(name){
		this.name = name;	
	}
}
class Cat extends Animal{
	constructor(name,type){
		super(name);
		this.type = type;
	}	
	renderHTML(){
		console.log(`rendering HTML...`);
		//variable only exists while block is executing...
		let divElement = document.createElement('div');
		//this should be only reference....
		divElement.addEventListener('click',this.testInstanceLife.bind(this));
		divElement.innerHTML = this.name;
		document.body.appendChild(divElement);
		//remove from DOM interface....
		document.body.removeChild(divElement);
		console.log(`there should be 0 references to this instance, since the divElement should be removed after block execution..`);
	}
	testInstanceLife(){
		console.log(this);
	}
}
//init
(()=>{
	document.addEventListener('DOMContentLoaded',()=>{
		var cat = new Cat('grumpy','tabby');
		cat.renderHTML();
		cat = null;
		console.log(`this object is now: ${cat}`);
		console.log(`finished executing...`);
	});
})();




问题:为什么异步超时和/或实例方法仍然引用自身,即使它们在执行之前都设置为null

0 个答案:

没有答案