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="https://www.cnblogs.com/lanshanxiao/p/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="https://www.cnblogs.com/lanshanxiao/p/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="https://www.cnblogs.com/lanshanxiao/p/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
效果展示:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/100535.html
標籤:JavaScript
下一篇:JS 同步轉異步之Promise
