• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
何YY
博客园    首页    新随笔    联系   管理    订阅  订阅

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
posted @ 2014-03-25 12:03  何YY  阅读(2632)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3