js对象的拷贝
2018-03-28 11:17
344 查看
对象浅复制Object.prototype.clone = function(){
var newObj = {};
for(var i in this){
newObj[i] = this[i];
}
return newObj;
}上面代码只复制对象的基本类型属性。
对象深拷贝Object.prototype.clone = function(){
var newObj = {};
for(var i in this){
if(typeof this[i]=="object"||typeof this[i]=="function"){
newObj[i] = this[i].clone();
}else{
newObj[i] = this[i];
}
}
return newObj;
}
Array.prototype.clone = function(){
var newArr = {};
for(var i=0;i<newArr.length;i++){
if(typeof this[i]=="object"||typeof this[i]=="function"){
newArr[i] = this[i].clone();
}else{
newArr[i] = this[i];
}
}
return newArr;
}
Function.prototype.clone = function(){
var that = this;
var newFun = function(){
return that.apply(this,arguments);
}
for(var i in this){
newFun[i] = this[i];
}
return newFun;
}深拷贝要实现基本数据类型,还有多种不等同对象,对象内部还有复杂结构,所以要用到递归。
var newObj = {};
for(var i in this){
newObj[i] = this[i];
}
return newObj;
}上面代码只复制对象的基本类型属性。
对象深拷贝Object.prototype.clone = function(){
var newObj = {};
for(var i in this){
if(typeof this[i]=="object"||typeof this[i]=="function"){
newObj[i] = this[i].clone();
}else{
newObj[i] = this[i];
}
}
return newObj;
}
Array.prototype.clone = function(){
var newArr = {};
for(var i=0;i<newArr.length;i++){
if(typeof this[i]=="object"||typeof this[i]=="function"){
newArr[i] = this[i].clone();
}else{
newArr[i] = this[i];
}
}
return newArr;
}
Function.prototype.clone = function(){
var that = this;
var newFun = function(){
return that.apply(this,arguments);
}
for(var i in this){
newFun[i] = this[i];
}
return newFun;
}深拷贝要实现基本数据类型,还有多种不等同对象,对象内部还有复杂结构,所以要用到递归。
相关文章推荐
- 详解js中对象的深浅拷贝
- JS的继承是从一个对象原型向另一个对象原型的简单拷贝
- Javascript_Js对象浅拷贝和深拷贝详解
- js对象深拷贝
- JS对象深拷贝
- js 对象的深拷贝
- js中对象的拷贝(复制)
- js 对象深拷贝
- JS中有关对象的继承以及实例化、浅拷贝深拷贝的奥秘
- 超实用的JavaScript代码段 Item8 -- js对象的(深)拷贝
- 由于js对象浅拷贝导致的遍历出错
- js对象深拷贝
- js 数组的深浅拷贝 js对象的深浅拷贝
- JS 对象引用和深拷贝
- js 数组对象的深浅拷贝
- js对象的深拷贝和浅拷贝
- js对象的深层 拷贝
- js对象的深浅拷贝
- JS对象的引用,对象的拷贝
- js 对象浅拷贝和深拷贝