码迷,mamicode.com
首页 > 编程语言 > 详细

编写 javascript 深度克隆函数 deepClone

时间:2016-10-06 20:03:04      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:

function deepClone(obj) {
    var _toString = Object.prototype.toString;

    // null, undefined, non-object, function
    if (!obj || typeof obj !== ‘object‘) {
        return obj;
    }

    // DOM Node
    if (obj.nodeType && ‘cloneNode‘ in obj) {
        return obj.cloneNode(true);
    }

    // Date
    if (_toString.call(obj) === ‘[object Date]‘) {
        return new Date(obj.getTime());
    }

    // RegExp
    if (_toString.call(obj) === ‘[object RegExp]‘) {
        var flags = [];
        if (obj.global) { flags.push(‘g‘); }
        if (obj.multiline) { flags.push(‘m‘); }
        if (obj.ignoreCase) { flags.push(‘i‘); }

        return new RegExp(obj.source, flags.join(‘‘));
    }

    var result = Array.isArray(obj) ? [] :
        obj.constructor ? new obj.constructor() : {};

    for (var key in obj ) {
        result[key] = deepClone(obj[key]);
    }

    return result;
}

function A() {
    this.a = a;
}

var a = {
    name: ‘qiu‘,
    birth: new Date(),
    pattern: /qiu/gim,
    container: document.body,
    hobbys: [‘book‘, new Date(), /aaa/gim, 111]
};

var c = new A();
var b = deepClone(c);
console.log(c.a === b.a);
console.log(c, b);

编写 javascript 深度克隆函数 deepClone

标签:

原文地址:http://www.cnblogs.com/xiaochechang/p/5934323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!