zoukankan      html  css  js  c++  java
  • 编写方法,深度克隆一个对象

    【要求】:编写方法,深度克隆一个对象

    【实现1】:

    Object.prototype.clone = function(){
        //原型指向保持一致
        var newobj = Object.create(Object.getPrototypeOf(this));
        //自身属性保持一样
        var propNames = Object.getOwnPropertyNames(this);
        propNames.forEach(function(item){
           //保持每个属性的特性也一样
           var des = Object.getOwnPropertyDescriptor(this,item);
           Object.defineProperty(newobj,item,des);
        },this);
        return newobj;
    }
    

    【实现2】:

    //深度克隆一个对象
    Object.prototype.clone=function(){
        var obj2=this.constructor===Array? []:{};
        
        if(typeof this !== "object") {
            return;
        } else {
            for(var i in this) {
                if(typeof this[i]==="object") {
                    obj2[i] = this[i].clone();
                } else {
                    obj2[i] = this[i];
                } 
            }
        }
        
        return obj2;
    }
    

    出处:忘了。。。

  • 相关阅读:
    TS之类的继承
    TS之函数及函数传参
    TS之数据类型
    Linux 协程
    设计模式 装饰器模式和代理模式
    C/C++ C和C++的区别
    C/C++ 内存分配方式
    Linux 进程间通信
    C/C++ RTTI
    Reactor设计模式
  • 原文地址:https://www.cnblogs.com/Ruth92/p/6143743.html
Copyright © 2011-2022 走看看