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); };