JavaScript实现对象克隆函数clone, 的程序及分析

程序:

<script type="text/javascript">

Object.prototype.Clone = function()

{

var objClone;

if ( this.constructor == Object ) objClone = new this.constructor(); //判断构造器是否为Object,因为还可能是String、Boolean等

else objClone = new this.constructor(this.valueOf());

for ( var key in this )

{

if ( objClone[key] != this[key] )

{

if ( typeof(this[key]) == 'object' )//如果是对象,就递归循环

{

objClone[key] = this[key].Clone();

}

else

{

objClone[key] = this[key];

}

}

}

objClone.toString = this.toString;

objClone.valueOf = this.valueOf;

return objClone;

}

a = {k1:1, k2:2, k3:3};

b = a.Clone();

b.k1=4;

alert(b.k1);

alert(a.k1);

</script>

分析:

1、JavaScript constructor 属性:constructor 属性返回对创建此对象的数组函数的引用。http://www.w3school.com.cn/jsref/jsref_constructor_array.asp

<script type="text/javascript">

var test=new Array();

if (test.constructor==Array)

{

document.write("This is an Array");

}

if (test.constructor==Boolean)

{

document.write("This is a Boolean");

}

if (test.constructor==Date)

{

document.write("This is a Date");

}

if (test.constructor==String)

{

document.write("This is a String");

}

</script>

输出:

This is an Array
2、JavaScript对象数据结构基本形式:{ key : value},其中key:value就为对象的一个属性,key作为属性名称,value为属性值,这值可以是任何JavaScript数据类型。http://www.jb51.net/article/20305.htm