26.JavaScript实现对象混合与对象浅度克隆和对象的深度克隆
程序员文章站
2022-04-15 22:52:34
JavaScript实现对象混合与对象浅度克隆和对象的深度克隆 1.实现对象混合: this.myPlugin = this.myPlugin || {}; /** * 将obj2混合到obj1产生新对象 * 实现方式1 */ this.myPlugin.mixObj = function (obj ......
javascript实现对象混合与对象浅度克隆和对象的深度克隆
1.实现对象混合:
this.myplugin = this.myplugin || {}; /** * 将obj2混合到obj1产生新对象 * 实现方式1 */ this.myplugin.mixobj = function (obj1, obj2) { var newobj = {}; //把obj2对象中的所有属性和值,赋值到newobj中 for (var prop in obj2) { if (obj2.hasownproperty(prop)) { //obj2继承的属性不被混合 newobj[prop] = obj2[prop]; } } //找到obj1中有但是obj2中没有的属性 for (var prop in obj1) { if (obj1.hasownproperty(prop) && !(prop in obj2)) { newobj[prop] = obj1[prop]; } } return newobj; } /** * 将obj2混合到obj1产生新对象 * 实现方式2 */ this.myplugin.mixobj = function (obj1, obj2) { return object.assign({}, obj1, obj2); }
调用对象混合:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title> </head> <body> <script src="./js/myplugin.js"></script> <script> var obj1 = { x:1, y:2, z:3 } var obj2 = { x:"abc", a:4, y:"bcd" } var obj = myplugin.mixobj(obj1, obj2); console.log(obj); </script> </body> </html>
效果展示:
2.实现对象浅度克隆和深度克隆
this.myplugin = this.myplugin || {}; /** * 把某个对象进行浅度克隆或深度克隆 * @param {boolean} deep 是否深度克隆,默认false */ this.myplugin.clone = function (obj, deep) { if (array.prototype.isprototypeof(obj)) { //是数组 if (deep) { //深度克隆 var newobj = []; for (var i = 0; i < obj.length; i++) { newobj.push(this.clone(obj[i], deep)); } return newobj; } else { return obj.slice(); //返回一个数组 } } else if ((typeof obj === "object") && (typeof obj !== null)) { var newobj = {}; for (var prop in obj) { if (obj.hasownproperty(prop)) { if (deep) { newobj[prop] = this.clone(obj[prop], deep); } else { newobj[prop] = obj[prop]; } } } return newobj; } else { //函数、原始类型:null, string, undefined, boolean, number return obj; //递归的终止条件 } }
调用对象浅度克隆:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title> </head> <body> <script src="./js/myplugin.js"></script> <script> var obj1 = { array:[ function(){}, null, "string", undefined, 1, false ], obj:{ value1:null, value2:undefined, value3:"string", value4:1, value5:true } } </script> </body> </html>
效果展示:
调用对象深度克隆:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title> </head> <body> <script src="./js/myplugin.js"></script> <script> var obj1 = { array:[ function(){}, null, "string", undefined, 1, false ], obj:{ value1:null, value2:undefined, value3:"string", value4:1, value5:true } } </script> </body> </html>
效果展示:
上一篇: 90%的人不知道这16个Python技巧
下一篇: php实现网站运行时间