7

Deep cloning an object in JS

 3 years ago
source link: https://gist.github.com/EkaterinaaTM/e7fd61be33d4a851131e7933b5a26cc4
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Deep cloning an object in JS · GitHub

Instantly share code, notes, and snippets.

var object_create = Object.create; if (typeof object_create !== 'function') { object_create = function(o) { function F() {} F.prototype = o; return new F(); }; } function deepClone(src) { if(src === null || typeof(src) !== 'object'){ return src; }

//Honor native/custom clone methods if(typeof src.clone == 'function'){ return src.clone(true); }

//Special cases: //Date if(src instanceof Date){ return new Date(src.getTime()); } //RegExp if(src instanceof RegExp){ return new RegExp(src); } //DOM Element if(src.nodeType && typeof src.cloneNode == 'function'){ return src.cloneNode(true); }

//Array if (Object.prototype.toString.call(src) == '[object Array]') { //[].slice() by itself would soft clone var ret = src.slice();

var i = ret.length; while (i--) { ret[i] = deepCopy(ret[i]); } return ret; }

//If we've reached here, we have a regular object var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__); var dest = object_create(proto); for (var key in src) { //Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc. dest[key] = deepCopy(src[key]); } return dest; }


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK