zoukankan      html  css  js  c++  java
  • 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>

  • 相关阅读:
    Android开发环境搭建全程演示(jdk+eclip+android sdk)
    mysql UDF接口 网络编程(代码改进版非阻塞,超时重传)
    HTTP_POST———使用mysql_udf与curl库完成http_post通信模块(mysql_udf,multi_curl,http,post)
    Linux自动更新时间
    CentOS下设置Mysql的root密码
    CentOS yum安装LAMP环境
    Nagios远程监控软件的安装与配置详解
    Android开发之旅:环境搭建及HelloWorld
    CentOS 6.3安装配置LAMP服务器(Apache+PHP5+MySQL)
    c#,winform,show,showdialog,子窗体,父窗体,传值,输入正确
  • 原文地址:https://www.cnblogs.com/cdwp8/p/4007419.html
Copyright © 2011-2022 走看看