前提:
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);