JS
//【示例】在下面示例中,先定义一个析构函数,该函数中包含一个析构方法,把该方法继承给任意对象,就可以调用它清除对象内部所有成员。
function D(){ // 析构函数
}
D.prototype = { // 析构函数原型对象
d : function(){ // 析构方法
for( var i in this ){ // 遍历当前对象
if( this[i] instanceof D ){ // 如果发现包含析构函数的实例
this[i].d(); // 则递归调用析构方法
}
this[i] = null; // 设置对象成员的值为null,即清除成员
}
}
}
function F(){ // 试验函数
this.x = 1;
this.y = function(){
alert( 2 );
}
}
F.prototype =new D(); // 绑定析构函数,继承析构方法
var f = new F(); // 实例化试验函数
f.d(); // 调用析构方法
alert(f.x); // 返回null,说明属性已经被注销
f.y() // 返回编译错误,说明方法已不存在