/**
* 方法一 在Object.prototype中添加clone();
*/
Object.prototype.clone = function () {
var o = this instanceof Array ? [] : {};
for (var attr in this) {
if (typeof this[attr] == "object") {
o[attr] = this[attr].clone();
continue;
}
o[attr] = this[attr]
}
return o;
};
/*
test
----------------------------------------------------------
*/
var obj = {
a: 3,
b: "p",
c: false,
d: function (e) {
console.log(e);
},
e:undefined,
arr: [1, 3, {
a: 1,
b: "2",
arr: [1, , 3]
}]
};
var object = obj.clone();
object.arr[2].arr[0] = 4;
console.log(obj.arr[2].arr[0]);
console.dir(object)
console.log(JSON.stringify(obj));
console.log(JSON.stringify(object));
/**
* 或者定义一个copy();
* 事实证明 JavaScript的类型自动转换能力真的很强将所有基本类型都包装了 instanceof Object is true (坑爹).
*/
function copy(obj) {
if (!(obj instanceof Object)){
return obj;
}
var o = obj instanceof Array ? [] : {};
for (var attr in obj) {
if (typeof obj[attr] == "object") {
o[attr] = copy(obj[attr]);
} else {
o[attr] = obj[attr];
}
}
return o;
}
/*
test
----------------------------------------------------------
*/
var obj = {
a: 3,
b: "p",
c: false,
d: function (e) {
console.log(e);
},
arr: [1, 3, {
a: 1,
b: "2",
arr: [1, 2, 3, {
a: "c",
arr: ["8", 1],
}]
}]
};
console.log(copy(4));
var o = copy(obj);
o.arr[2].arr[2] = 4;
console.log(JSON.stringify(obj));
console.log(JSON.stringify(o));