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); }myPlugin.js
調用對象混合:
<!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>index.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; //遞歸的終止條件 } }myPlugin.js
調用對象淺度克隆:
<!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>index.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>index.html
效果展示: