oldObj = {
prop: 'old',
sonObj: {
name: 'old'
}
}
已經(jīng)分不清什么淺拷貝了
淺拷貝
newObj111 = oldObj
一級拷貝
newObj222 = Object.assign({}, oldObj,{prop1: '1'}) // sunObj 仍然引用的地址
newObj222.__proto__
// {constructor: ?, __defineGetter__: ?, __defineSetter__: ?, hasOwnProperty: ?, __lookupGetter__: ?, …}
newObj333 = Object.create(oldObj) // 創(chuàng)建的對象擁有明確的原型
newObj333.__proto__
// {name: "xiaoming", age: 23, sonObj: {…}}age: 23name: "xiaoming"sonObj: {name: 3}__proto__: Object
underscore
var obj = _.cloneDeep(oldObj);
深拷貝
json 裝換
// 不能轉換 function 和 regExp
var obj1 = { fun: function(){ console.log(123) } };
var obj2 = JSON.parse(JSON.stringify(obj1));
// {}
函數(shù)
function deepClone (oldObj) {
let newObj = {}
for (let i in oldObj) {
const value = oldObj[i]
if (typeof value === 'Object' || typeof value === 'Array') {
newObj[i] = deepCopy(value)
} else {
newObj[i] = oldObj[i]
}
}
return newObj
}
newObj444 = deepClone(oldObj)
函數(shù)改版(最佳實踐)
jQuery
var obj = $.extend(true, {}, oldObj);
Lodash
var obj = _.cloneDeep(oldObj);
內(nèi)容淺顯,歡迎糾錯補充