• 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>

  • 相关阅读:
    leetcode 337. House Robber III
    leetcode 366 Find Leaves of Binary Tree
    leetcode 250 Count Univalue Subtrees
    leetcode 132 Palindrome Pairs 2
    leetcode 131 Palindrome Pairs
    leetcode 336 Palindrome Pairs
    leetcode 214 Shortest Palindrome
    leetcode 9 Palindrome Number
    Socket编程
    Zookeeper
  • 原文地址:https://www.cnblogs.com/cdwp8/p/4007419.html
Copyright © 2020-2023  润新知