I saw a blog post about the deep copy method of Json objects before, that is,
var obj = {
sayName: function() {
alert(this.name);
},
name:'Jingshuiyuan'
};var cloneObj=JSON.parse (JSON.stringify(obj));cloneObj.sayName();
But in this way, the attribute value cannot be copied as the attribute of the function, so the method has been improved. The following is the specific code:
var obj = {
sayName: function() {
alert(this.name);
},
name:'Still Water Abyss'
};
function clone(){
var str,newObj;
str= JSON .stringify(obj, function(key, value) {
return (typeof value == 'function' ? value.toString().replace(/^function(.*)/g, "jsonFunction$1") : value );
});
newObj = JSON.parse(str, function (key, value) {
if (/^jsonFunction(.*)/.test(value)) {
var strFun = '(' value.replace(/^jsonFunction(.*)/, "function$1") ')';
value = eval(strFun);
}
return value;
});
return newObj;
}
var cloneObj=clone(obj);
cloneObj.sayName();
Because it has not been fully tested yet, welcome Shoot bricks!