javascript深度克隆与javascript的继承实现
1、javascript深度克隆:
//注意这里的对象包括object和array
function cloneObject(obj){
var o = obj.constructor === Array ? [] : {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
o[key] = typeof obj[key] === "object" ? cloneObject(obj[key]) : obj[key];
}
}
return o;
}
Object.prototype.cloneObject=function(){
var o=this.constructor===Array?[]:{};
for(var key in this){
if(this.hasOwnProperty(key)){
o[key] = typeof this[key] === "object" ? cloneObject(this[key]) : this[key];
}
}
return o;
}
//这个方法只能用于被拷贝的对象中元素中没有引用类型的值。
Object.prototype.cloneObject=function(){
var str=JSON.stringify(this);
return JSON.parse(str);
}
2、javascript的继承实现:
第一种 prototype 引用型原型继承
<script>
function parent(){
this.x=10;
}
function child(){
}
child.prototype=new parent();
var childObj=new child();
alert(childObj.x);
</script>
第二种 类继承 属性抄写
<script>
function parent(){
this.x=10;
}
function child(){
var parentObj=new parent();
for(var p in parentObj)this[p]=parentObj[p];
}
var childObj=new child();
alert(childObj.x);</script>
第三种 类继承 对象冒充
<script>
function parent(){
this.x=10;
}
function child(){
parent.call(this);
}
var childObj=new child();
alert(childObj.x);
</script>
第四种 原型抄写
<script>
function parent(){}
parent.prototype.me=function(){alert("parent")};
function child(){}
for(var p in parent.prototype){
child.prototype[p]=parent.prototype[p];
}
var childObj=new child();
childObj.me();
</script>
第五种 混合方式
混合了call方式、原型链方式
<script>
function Parent(hello){
this.hello = hello;
}
Parent.prototype.sayHello = function(){
alert(this.hello);
}
function Child(world){
Parent.call(this);//将父类的属性继承过来
this.world = world;//新增一些属性
}
Child.prototype = new Parent();//将父类的方法继承过来
Child.prototype.sayWorld = function(){//新增一些方法
alert(this.world);
}
var c = new Child("zhangsan","lisi");
c.sayHello();
c.sayWorld();
</script>
最新文章
- SharePoint 2007 User Re-created in AD with new SID issue on MySite
- GCD in Swfit 3.0
- Linux打包压缩.md
- 理解Docker单机容器网络
- Docker简介
- HTML5、CSS3各浏览器兼容性
- ListCtrl控件着色
- c#Message多功能用法
- android wear开发:为可穿戴设备创建一个通知 - Creating a Notification for Wearables
- php 后端跨域请求
- 【洛谷P3014】Cow Line
- springboot 启动报错
- Egret飞行模拟-开发记录02
- JS怎样实现图片的懒加载以及jquery.lazyload.js的使用
- 2015-10-15 css3
- 手动升级11.2.0.1的rac数据库到11.2.0.4
- BZOJ 5099: Pionek(双指针)(占位)
- TortoiseGit disconnected no supported authentication
- Linux+Nginx+Asp.net Core及守护进程部署
- delphi TStringList 用法详解
热门文章
- unity3d自己写角色移动脚本
- GCC 编译命令
- Java面试题:n=2\n1*2*5*6\n--3*4\n\nn=3\n1*2*3*10*11*12\n--4*5*8*9\n----6*7\n如何实现如上结构的数据
- 类内const static(static const)成员变量初始化问题
- uvalive 4513 Stammering Aliens
- UIImagePickerController Class 概述
- Asp.Net底层解析
- jquery foreach
- hql查询技巧
- EASYUI- EASYUI左移右移 GRID中值