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

javascript实现深克隆的几种方法

时间:2016-03-29 12:36:18      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

1)普通函数实现

function cloneObject(obj) {
            if (obj === null || typeof obj !== ‘object‘) {
                return obj;
            }
            var temp = obj.constructor(); // give temp the original obj‘s constructor
            for (var key in obj) {
                temp[key] = cloneObject(obj[key]);
            }
            return temp;
}
        var bob = {
            name: "Bob",
            age: 32
        };

        var bill = cloneObject(bob);
        bill.name = "Bill";

        console.log(bob);
        console.log(bill);

2)通过json方法实现

var bob = {
    name: "Bob",
    age: 32
};
 
var bill = (JSON.parse(JSON.stringify(bob)));
bill.name = "Bill";
 
console.log(bob);
console.log(bill);

3)jquery中的$.extend

var bob = {
    name: "Bob",
    age: 32
};
 
var bill = $.extend(true, {}, bob);
bill.name = "Bill";
 
console.log(bob);
console.log(bill);

 

 

  

javascript实现深克隆的几种方法

标签:

原文地址:http://www.cnblogs.com/hutuzhu/p/5332334.html

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