如何實現 JavaScript 對象的深拷貝?需要複製後的對象是全新的,所有的成員包括成員函數在內。
14 回复
function $clone(origin) {
if (typeof origin != "object") {
return origin;
}
var cloned;
if (origin instanceof Array) {
cloned = [];
for ( var i = 0; i < origin.length; i++) {
if (typeof origin[i] == "object") {
cloned[i] = $clone(origin[i]);
}
else {
cloned[i] = origin[i];
}
}
}
else {
cloned = {};
for ( var j in origin) {
if (typeof origin[j] == "object") {
cloned[j] = $clone(origin[j]);
}
else {
cloned[j] = origin[j];
}
}
}
return cloned;
};
@byvoid 你确定没有搞错? 测试下这个:
function Test() {
this.name = 'test';
}
function FatherTest() {
}
FatherTest.prototype.parts = [5,1,2];
FatherTest.prototype.printM = function(){
print('this is printM from Father:'+ this.sex);
};
Test.prototype = $clone(FatherTest.prototype);//深入拷贝
Test.prototype.sex = 'male';
var test = new Test();
print('-------key in test--------');
for(var key in test){
print(key +':'+test[key]);
}
print('-------test继承的方法--------');
test.sex = 'changed sex';
test.printM();
print('-------改变test的数组--------');
test.parts.push(3);
print(test.parts);
var father= new FatherTest();
print(father.parts);//不再会被test.parts.push(3);影响
print('-------instanceof--------');
print(test.parts instanceof Array);
看下结果,可以解答你的问题了
@byvoid 请问为何要拷贝Date,Date是js中的引用类型,如何去复制,就像你无法去复制Object一样。另你所说的instanceof,请参考我的代码。
function ss(){
this.name='ss';
this.test=['a','b','c'];
}
ss.prototype.age='12';
ss.prototype.sayName=function(){
alert(this.name);
}
function subObject(o){
function b(){};
b.prototype=o;
return new b();
}
var cc=subObject(new ss());
var dd=subObject(new ss());
cc.name='I\'m cc';
dd.test.push('d');
for (var key in cc){
console.log(key+':'+cc[key]);
}
for (var key in dd){
console.log(key+':'+dd[key]);
}
var ee=subObject(new Date());
alert(ee instanceof Date); //true 没有继承任何date的方法
@sumory 這個例子,無論複製 obj1 還是 obj2 ,都會棧溢出。
var obj1 = {
ref: null
};
var obj2 = {
ref: obj1
};
obj1.ref = obj2;