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>

转载于:https://www.cnblogs.com/cdwp8/p/4007419.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值