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

javascript 对象的复制

时间:2016-04-18 11:33:10      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

1.  jQuery has a method that can be used to deep-clone objects, the$.extend() function. Let’s take a look at how it can be used:

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

注意:Pretty handy, eh? This method is a little slower than the JSON exploit, but that shouldn’t really be a problem when you’re only doing a few clones. If you’re doing hundreds or thousands of clones, it might be time to think about the JSON exploit or another solution.

 

2.   A clever exploit of the JSON library to deep-clone objects

We can exploit the JSON library for a rather fast way of deep-cloning objects. Check it out:

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

3.  tipJS中的一个方法,也不错 ,不过我自己还没完全理解这个方法的独到之处(或者说这个方法的用途)

util__.cloneObject = function(obj, isFlat){
		var newObj, k;
		if (obj == null || typeof obj != "object") return obj;
		if (!isFlat) {
			newObj = (obj instanceof Array) ? [] : {};
			for (k in obj) {
				if (typeof obj[k] == "object") newObj[k] = util__.cloneObject(obj[k], false);
				else newObj[k] = obj[k];
			}
			return newObj;
		} else return __cloneObjN(obj);
	};


var __cloneObjN = function(target) {
		if (util__.isFunction(Object.create)) __cloneObjN = function(o) {	return Object.create(o); };
		else {
			__cloneObjN = function(o) {
				function F() {};
				F.prototype = o;
				return new F;
			};
		}
		return __cloneObjN(target);
	};

  

javascript 对象的复制

标签:

原文地址:http://www.cnblogs.com/oxspirt/p/5403497.html

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