/**
* 方法一 在Object.prototype中添加clone();
* RegExp 类型的对象调用JSON.stringify() 只会打印一个{}
*/
Object.prototype.clone = function () {
if (this === null || !(typeof this === "object")) {
return this;
} else if (Object.prototype.toString.call(this).slice(8, -1) === "Date") {
return new Date(this.getTime());
} else if (Object.prototype.toString.call(this).slice(8, -1) === "RegExp") {
var pattern = this.valueOf();
var flags = '';
flags += pattern.global ? 'g' : '';
flags += pattern.ignoreCase ? 'i' : '';
flags += pattern.multiline ? 'm' : '';
return new RegExp(pattern.source, flags);
}
var o = Array.isArray(this) ? [] : {};
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, new Date(),/[^\d]/g , 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 === null || !(typeof obj === "object")) {
return obj;
} else if (Object.prototype.toString.call(obj).slice(8, -1) === "Date") {
return new Date(obj.getTime());
} else if (Object.prototype.toString.call(obj).slice(8, -1) === "RegExp") {
var pattern = obj.valueOf();
var flags = '';
flags += pattern.global ? 'g' : '';
flags += pattern.ignoreCase ? 'i' : '';
flags += pattern.multiline ? 'm' : '';
return new RegExp(pattern.source, flags);
}
// var o = isArray(obj) ? [] : {};
var o = Array.isArray(obj) ? [] : {};
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(null));
console.log(copy(4));
var o = copy(obj);
o.arr[2].arr[2] = 100;
console.log(JSON.stringify(obj));
console.log(JSON.stringify(o));
/*
附Array.isArray的具体实现方法! ECMAScript5已经实现!
为什么不用instanceof? 因为很多时候instanceof不可靠 比如对象所在Windows不同时!
*/
function isArray(obj) {
return typeof obj === "object" && Object.prototype.toString.call(obj).slice(8, -1) === "Array";
};