使用递归进行深拷贝
window.onload = function() { testCons(); Object.prototype.Clone = function() { var objClone; if (this.constructor == Object) { objClone = new this.constructor(); } else { // objClone=new this.constructor(this.valueOf()); objClone = this.valueOf();//似乎这样也没错? } for (var key in this) { if (objClone[key] != this[key]) { if (typeof(this[key]) == ‘object‘) { objClone[key] = this[key].Clone(); } else { objClone[key] = this[key]; } } } objClone.toString = this.toString; objClone.valueOf = this.valueOf; return objClone; } var obj1 = { key1: 1, key2: { key21: 21, key22:"22", key23:{ key221:221 } } } obj2 = obj1.Clone(); console.log(obj2); console.log(typeof obj2.key2.key21); } function testCons() { var num = 5; console.log(num.constructor(6)); //6 console.log(typeof num.constructor(6)); //number console.log(num.constructor);//function Number() { [native code] } console.log(num.constructor==Number);//true n=new num.constructor(6); console.log(typeof n); //object console.log(n.constructor);//function Number() { [native code] } console.log(n.constructor==Object); //false //因此用constructor来判断类型是最合适不过的 function Person(name) { this.name = name; } p1 = new Person(‘fgh‘); console.log(p1.constructor == Person); //true p2 = new p1.constructor(‘bnmn‘); console.log(p2.name); //bnmn //两者一致 console.log(Person); console.log(p2.constructor); }