Home  >  Article  >  Web Front-end  >  Improved version of deep copy method through Json object_json

Improved version of deep copy method through Json object_json

WBOY
WBOYOriginal
2016-05-16 17:48:521217browse

I saw a blog post about the deep copy method of Json objects before, that is,

Copy code The code is as follows:

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:
Copy code The code is as follows:

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!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn