1.引用传递是浅拷贝,传递的是地址 例如obj2的改变,obj1也会改变 1 var obj={ 2 name:"admin" 3 } 4 var obj2=obj 5 console.log(obj) //{name: "admin"} 6 console.log(obj2) //{name: "admin"} 7 8 obj2.name="root" 9 console.log
1.引用传递是浅拷贝,传递的是地址
例如obj2的改变,obj1也会改变
1 var obj={ 2 name:"admin" 3 } 4 var obj2=obj 5 console.log(obj) //{name: "admin"} 6 console.log(obj2) //{name: "admin"} 7 8 obj2.name="root" 9 console.log(obj) //{name: "root"} 10 console.log(obj2) //{name: "root"}
2深拷贝
2.1 深拷贝1:遍历对象读取每个键值对,逐个复制,但是后面会有缺点
2 var obj={ 3 name:"admin" 4 } 5 var obj2={}; 6 for(var i in obj){ 7 obj2[i]=obj[i] 8 } 9 console.log(obj) //{name: "root"} 10 console.log(obj2) //{name: "root"} 11 12 obj2.name="root"; 13 console.log(obj) //{name: "root"} 14 console.log(obj2) //{name: "root"} 15 16 缺点 17 var obj={ 18 name:{ 19 name1:"admin" 20 } 21 } 22 var obj2={}; 23 for(var i in obj){ 24 obj2[i]=obj[i] 25 } 26 console.log(obj) //name: {name: "admin"} 27 console.log(obj2) //name: {name: "admin"} 28 29 obj2.name.name1="root" 30 console.log(obj) //name: {name1: "root"} 31 console.log(obj2) //name: {name1: "root"} 32 此时会把obj内的属性值也会改变
2.2 深拷贝2:利用字符的值传递,将对象转成字符再转回来
1 var obj = { 2 name:{ 3 name1:{ 4 name2:"admin" 5 } 6 } 7 } 8 // JSON.parses是字符转对象,JSON.stringify是对象转字符 9 var obj2=JSON.parse(JSON.stringify(obj)); 10 console.log(obj) //obj 11 console.log(obj2) //obj 12 obj2.name.name1.name2="root"; 13 console.log(obj) //name:"root" 14 console.log(obj2) //name:"root"
2.3深拷贝3:利用Object.create()实现继承
1 var obj={ 2 name:"admin" 3 4 } 5 var obj2=Object.create(obj); 6 console.log(obj) //{name: "admin"} 7 console.log(obj2) //{} 8 9 obj2.name="root" 10 console.log(obj.name) //admin 11 console.log(obj2.name) //root 12 obj2.__proto__.name = "root" 13 console.log(obj.name) //root 14 console.log(obj2.name) //root// 相当于继承了原型,obj是obj2的父级,修改obj2不会影响obj,除非在obj2上修改原型