• JavaScript实现Object的clone


    前提:

    JavaScript中并没有提供对象的Clone方法,采用直接赋值的方法(var a = {key:'val'}; var b = a;)有一个很大的弊端:改变b的同时会改变a。所以,实现对象的clone方法是必要的。下面给出了几种实现方法。

    1.$.extend()方法

    var copiedObject = jQuery.extend({},originalObject);

    添加true参数实现deep copy

    var copiedObject = jQuery.extend(true, {}, originalObject);

    2.自定义简单的clone方法

        Object.prototype.clone = function() {
            var obj = this;
            var copy = (obj instanceof Array) ? [] : {};
            for(var attr in obj) {
                if(!obj.hasOwnProperty(attr))
                    continue;
                copy[attr] = (typeof obj[attr] == 'Object') ? obj[attr].clone() : obj[attr];
            }
            return copy;
        };
    
        var a = {name:'Sherry', age:12, interests:['Reading', 'Traveling', 'Running']};
        var b = a.clone();

    3.自定义的deep copy方法

        function clone(obj) {
            // Handle the 3 simple types, and null or undefined
            if (null == obj || "object" != typeof obj) return obj;
    
            // Handle Date
            if (obj instanceof Date) {
                var copy = new Date();
                copy.setTime(obj.getTime());
                return copy;
            }
    
            // Handle Array
            if (obj instanceof Array) {
                var copy = [];
                for (var i = 0, len = obj.length; i < len; i++) {
                    copy[i] = clone(obj[i]);
                }
                return copy;
            }
    
            // Handle Object
            if (obj instanceof Object) {
                var copy = {};
                for (var attr in obj) {
                    if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
                }
                return copy;
            }
    
            throw new Error("Unable to copy obj! Its type isn't supported.");
        }
    
        var a = {name:'Sherry', age:12, interests:['Reading', 'Traveling', 'Running']};
        var b = clone(a);

    Ref: Most elegant way to clone a JavaScript object

  • 相关阅读:
    ngnix之笔记
    nginx之"/"结尾
    nginx之root和alias区别
    Python3 操作Excel--openpyxl
    python学习笔记之线程、进程和协程(第八天)
    python之堡垒机(第九天)
    python学习笔记之socket(第七天)
    python学习笔记之paramiko和sqlalchemy (第九天)
    python之在线PK游戏(第六天)
    python学习笔记之类class(第六天)
  • 原文地址:https://www.cnblogs.com/SherryIsMe/p/3480333.html
Copyright © 2020-2023  润新知