我想知道如何正确“清除”一个对象实例。 使用下面的代码,内部setInterval()即使在父实例被“清除”之后仍将继续运行。如何在javascript中删除/清除/忘记对象实例?
// simple Class
var aClass = function(){
return {
init: function(){
console.log("aClass init()")
setInterval(this.tick, 1000);
// note: we're not storing the ref
},
tick: function(){
console.log("aClass tick");
}
}
}
// instantiate the class
var inst = new aClass();
inst.init();
// try to forget the instance
function test(){
console.log("test() 1 inst:", inst);
inst = null;
console.log("test() 2 inst:", inst);
}
// run for a while, then call test()
setTimeout(test, 4000);
输出:
aClass init()
aClass tick
aClass tick
aClass tick
test() 1 inst: {.....}
test() 2 inst: null
aClass tick
aClass tick ...
问题是, “ACLASS嘀” 消息继续试验后打印()。
想法?
'setInterval'及其处理程序无关,与你的对象。 – VisioN
@VisioN - OP的观点是,如果对象的引用保持在闭包中,则该对象不会真的被“删除”。 – nrabinowitz
该对象被删除,inst在第二个控制台日志中为空。当用作setInterval的参数时,函数节点被复制。 – HMR