js對象拷貝的方法


 對象拷貝的方法是一個難點,尤其是深拷貝。建議把代碼都運行下,幫助理解拷貝。

一. json方法

1. 適合情況
 JSON對象的深度克隆。方法是先JSON.stringify() 轉為json字符串, 再JSON.parse() 轉為json數組

2. 缺點:
  a. 如果你的對象里有函數, 函數無法被拷貝下來
  b. 無法拷貝copyObj對象原型鏈上的屬性和方法

var obj = {
    x: 1,
    y: {
        a: 1,
        b: 0,
        c: [1, 2, 3]
    }
};

// 相同的引用
var obj2 = obj;
console.log(obj2 == obj); //true 直接復制只是復制對象的指針,還指向同一個對象

//不同的引用
var obj3 = JSON.parse(JSON.stringify(obj));
console.log(obj3 == obj) //false  通過json方法復制后的地址不一樣
console.log(obj3);

二. jQuery extend方法

jQuery.extend(object)

概述:
 擴展jQuery對象本身,用來在jQuery命名空間上增加新函數。

var obj = {
    x: 1,
    y: {
        a: 1,
        b: 0,
        c: [1, 2, 3]
    }
};
var obj2 = $.extend({}, obj);
console.log(obj2 == obj) //false  復制后的地址不一樣
console.log(obj2);

在這里插入圖片描述

三. Object.create()方法

 復制對象存在於Object原型prototype中

var obj = {
    x: 1,
    y: {
        a: 1,
        b: 0,
        c: [1, 2, 3]
    }
};

var obj2 = Object.create(obj);
console.log(obj2 == obj); //false
console.log(obj2);

在這里插入圖片描述

四. for循環遍歷方法

1. 淺拷貝:
 只是拷貝了基本類型的數據;然而引用類型數據, 只是復制了指針,復制后也是會發生引用。
 除了這個是淺拷貝,本文章介紹的其他方法都是深拷貝。

var obj = {
    x: 1,
    y: {
        a: 1,
        b: 0,
        c: [1, 2, 3]
    }
};

var obj2 = {};

for (var i in obj) { //for in 會遍歷對象的屬性,包括實例中和原型中的屬性。(需要可訪問,可枚舉屬性)
    obj2[i] = obj[i];
}
console.log(obj2);

obj2.y.c.push(4); //給新數組添加一個元素4,會同步反映在新舊數組中
console.log(obj2.y.c); // [1,2,3,4]
console.log(obj.y.c); // [1,2,3,4]  淺拷貝只是復制了地址,修改是內存中的數據

2. 深拷貝
 深拷貝, 就是遍歷那個被拷貝的對象。判斷對象里每一項的數據類型。如果不是對象類型, 就直接賦值, 如果是對象類型, 就再次調用遞歸的方法去賦值。

var obj = {
    x: 1,
    y: {
        a: 1,
        b: 0,
        c: [1, 2, 3]
    }
};

function getClass(o) { //判斷數據類型
    return Object.prototype.toString.call(o).slice(8, -1);
}

function deepCopy(obj) {
    var result, oClass = getClass(obj);

    if (oClass == "Object") result = {}; //判斷傳入的如果是對象,繼續遍歷
    else if (oClass == "Array") result = []; //判斷傳入的如果是數組,繼續遍歷
    else return obj; //如果是基本數據類型就直接返回

    for (var i in obj) {
        var copy = obj[i];

        if (getClass(copy) == "Object") result[i] = deepCopy(copy); //遞歸方法 ,如果對象繼續變量obj[i],下一級還是對象,就obj[i][i]
        else if (getClass(copy) == "Array") result[i] = deepCopy(copy); //遞歸方法 ,如果對象繼續數組obj[i],下一級還是數組,就obj[i][i]
        else result[i] = copy; //基本數據類型則賦值給屬性
    }

    return result;
}

var obj2 = deepCopy(obj);
console.log(obj2);

在這里插入圖片描述

五. 原型鏈繼承方法

function Father() {
    this.say = "hi";
    this.fn = function () {
        return this.say;
    }
}

Father.prototype.eat = function () {
    console.log('吃');
}

function Son() {
    this.play = function () {
        console.log('play game');
    }
}

//通過原型來繼承父類的公共屬性
Son.prototype = new Father();
var s = new Son();

console.log(s);
console.log(s.say); //hi
console.log(s.fn()); //hi

在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM