之前看到部落格的關於Json物件的深複製方法,即
var obj = {
sayName: function() {
alert(this.name);
},
name:'靜水淵'
};var cloneObj=JSON.parse (JSON.stringify(obj));cloneObj.sayName();
但這種方式,不能複製屬性值是函數的屬性,因此改進了方法,以下是具體程式碼:
var obj = {
sayName: function() { alert(this.name);
},
name:'靜水淵'
};
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();
因為還沒全面測試過,歡迎拍磚!