github源码:https://github.com/fypShirley...

看下面的示例了解赋值和引用的区别:

赋值:
    var a = 5;
    var b = a;
    b+=3;
    
    console.log(b)//8
    console.log(a)//5 原值没有发生改变

引用:(对象和函数都是引用的关系)
    var a = [1,2,3];
    var b = a;
    var c = a;
    b.push(4);
    
    console.log(b);//[1,2,3,4]
    console.log(a);//[1,2,3,4] a被影响
    
    c = [1,2,3,4,5];
    console.log(c);//[1,2,3,4,5]
    console.log(a);//[1,2,3,4] a不受影响
    

浅拷贝:

   var obj0= {a:10};
   var obj1= {a:{b:10}};
   
   function copy(obj){//浅拷贝
       var newObj = {};

       for(var attr in obj){
           newObj[attr] = obj[attr];
       }
       return newObj;
   }
   
    var obj2 = copy(obj0);
    var obj3 = copy(obj1);
    obj3.a.b = 20;
    
    console.log(obj0.a);//10 a不受影响
    console.log(obj1.a.b);//20 受影响了,还是引用
    

深拷贝:

先看一个递归 :
 function test(n){
    if(n == 1){
        console.trace()
        return 1;
    }
    return n*test(n-1);
}
console.log(test(4))//1*2*3*4 -> 24
深拷贝利用递归的思想:
function deepCopy(obj){//一层层进入,拿到值
   if(typeof obj != 'object'){
       return obj;
   }
   console.trace();
   var newObj = {};

   for(var attr in obj){
       newObj[attr] = deepCopy(obj[attr]);//递归
   }
   return newObj;
 }
 var obj4= {a:{b:10}};
 var obj5 = deepCopy(obj4);
 obj5.a.b = 20;
 console.log(obj4.a);//a->{b:10},原数据没有改变
 console.log(obj5.a);//a->{b:20},
 

再一个深/浅拷贝的对比

 //先声明一个对象parent:

 var parent = {
   numbers: [1, 2, 3],
   letters: ['a', 'b', 'c'],
   obj: {prop: 1   },
   bool: true
};

// 浅拷贝函数:
function extendCopy(p) {//传地址
   var c = {};
   for (var i in p) {
       c[i] = p[i];
   }
   c.uber = p;
   return c;
}


// 深拷贝函数:
function deepCopy(p, c) {//传值
//在拷贝每个属性之前,建议使用 hasOwnProperty()来确认不会误拷贝不需要的继承属性。
   c = c || {};
   for (var i in p) {
       //console.log(p.hasOwnProperty(i))
       if (p.hasOwnProperty(i)) {
           if (typeof p[i] === 'object') {
               c[i] = Array.isArray(p[i]) ? [] : {};
               deepCopy(p[i], c[i]);
           } else {
               c[i] = p[i];
           }
       }
   }
   return c;
}

var mydeep = deepCopy(parent);
mydeep.numbers.push(5);
console.log(mydeep.numbers)//[1,2,3,5]
console.log(parent.numbers)//[1,2,3]原数据没有改变

myshallow.numbers.push(6);
console.log(myshallow.numbers)//[1,2,3,6]
console.log(parent.numbers)//[1,2,3,6原数据改变
console.log(mydeep.numbers)//[1,2,3]


平平不平
343 声望18 粉丝