Home > Web Front-end > JS Tutorial > body text

Improved version of deep copy method through Json object_json

WBOY
Release: 2016-05-16 17:48:52
Original
1248 people have browsed it

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!
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template