我正在使用John Resig的JavaScript '类'和继承方案。为了提问,我将我的代码简化为以下内容:
MyClass = Class.extend({
// create an <h3>Hello world!</h3> in the HTML document
init : function (divId) {
this._divId = divId;
this._textDiv = document.createElement("h3");
this._textDiv.innerHTML = "Hello world!";
document.getElementById(divId).appendChild(this._textDiv);
},
// remove the <h3> and delete this object
remove : function () {
var container = document.getElementById(this._divId);
container.parentNode.removeChild(container);
// can I put some code here to release this object?
}
});
一切正常:
var widget = new MyClass("theDivId");
...
widget.remove();
我将在页面上拥有数百个这些东西(显然带有一些合理的功能),我希望有一种简单的方法来释放每个对象的内存。我知道可以使用widget = null;
并相信GC会在需要时释放对象,但是在remove()
方法中是否可以做一些明确的事情?我知道在remove()
的末尾放置this = null;
是不起作用的 ;)