js 对象深复制
发布日期:2022-02-08 04:21:00 浏览次数:2 分类:技术文章

本文共 3155 字,大约阅读时间需要 10 分钟。

深复制:源对象的属性如果有对象,该对象属性修改后,不会引起复制后的对象各属性的改变,源对象的任何属性及子属性,与新对象的没有任何引用关系。

简单来说就一句话,新对象与原对象,除了长得一样外,没有任何引用关系,两边更新修改互不影响。

var obj = {
a: 1, b: "a", c: true, d: function (a, b) {
if (a > 10) a = 10; if (b > 5) {
b = 5; } else if (b < 0) {
b = 0; } console.log(a + b); }, e: [1, 2, 3, 4], f: {
g: ["a", "b", "c"], h: new Date(), i: /^[a-z]+$/g, j: {
k: {
}, l: [true, false], m: [ {
id: 1001, name: "abc1" }, {
id: 1002, name: "abc2" }, {
id: 1003, name: "abc3" } ] } }}Object.defineProperties(obj.f.j, {
n: {
value: function () {
console.log("abcd"); } }, o: {
value: 10, enumerable: true }, p: {
value: [1, 2, 3], writable: true }, q: {
value: true, writable: true, enumerable: true }});Object.defineProperties(obj.f.j.k, {
r: {
value: function () {
}, writable: true }, s: {
value: {
a: 1 }, enumerable: true }});// console.log(obj);var obj1 = cloneObject(obj);obj.f.j.p[2] = 10;console.log(obj, obj1);function cloneObject(sourceObj, targetObj) {
// targetObj=targetObj || {}; if (!targetObj) {
// sourceObj.constructor就是 sourceObj的类型 // sourceObj是数组 sourceObj.constructor->Array new Array(); targetObj = new sourceObj.constructor(); switch (sourceObj.constructor) {
case RegExp: targetObj = new RegExp(sourceObj.source, sourceObj.flags); break; case Date: targetObj = new Date(sourceObj); break; } } var names = Object.getOwnPropertyNames(sourceObj); for (var i = 0; i < names.length; i++) {
// console.log(names[i],sourceObj[names[i]]); // console.log(typeof sourceObj[names[i]]); var desc = Object.getOwnPropertyDescriptor(sourceObj, names[i]); if (typeof desc.value === "object") {
var o = cloneObject(desc.value); Object.defineProperty(targetObj, names[i], {
enumerable: desc.enumerable, configurable: desc.configurable, writable: desc.writable, value: o }); } else if (typeof desc.value === "function") {
var fnStr = desc.value.toString().replace(/\n/g, ""); var arg = fnStr.match(/\((.*?)\)/)[1]; var content = fnStr.match(/{(.*)}/)[1]; var fn = new Function(arg, content); Object.defineProperty(targetObj, names[i], {
enumerable: desc.enumerable, configurable: desc.configurable, writable: desc.writable, value: fn }); } else {
Object.defineProperty(targetObj, names[i], desc); } } return targetObj;}

目标对象(新对象)与原对象,所有的属性一模一样,而且,更改新对象的任何属性,不会影响原对象的属性值。

在这里插入图片描述

转载地址:https://blog.csdn.net/weixin_43297321/article/details/104381366 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:js 对象 详解
下一篇:jQuery

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年03月21日 18时35分29秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章