In-depth analysis of object copy methods in JavaScript (with code)
In the previous article "What you need to know about the use of JavaScript "jquery inheritance" (detailed code explanation)", we learned about the use of JavaScript "jquery inheritance". The following article will introduce you to the object copy method in JS. Friends in need can refer to it.
When it comes to object copying in javascript
, the first thing we think of is Object.assign()
JSON.parse(JSON.stringify()),
and ES6
’s expansion operator [...
]
Because in js
=
operator cannot create a copy for an object, it is just a reference to the object
Operator
var x = { a: 1, b: 2, }; y = x; x.a = 10; console.log(x); //{a:10, b:2} console.log(y); //{a:10, b:2}
Therefore, when performing object operations, the equal operator (=
) is not advisable
Object.assign()
var x = { a: 1, b: 2, }; y = Object.assign({}, x); x.a = 10; console.log(x); //{a:10, b:2} console.log(y); //{a:1, b:2}
At first glance, it is not An exception will be found, because what we want is the result we want. If we make the object structure a little more complicated and look at it
var x = { a: 1, b: 2, c: { d: 3, }, }; y = Object.assign({}, x); x.a = 5; console.log(x); //{a:5, b:2, c:{d:3}} console.log(y); //{a:5, b:2, c:{d:3}} x.c.d = 10; console.log(x); //{a:5, b:2, c:{d:10}} console.log(y); //{a:5, b:2, c:{d:10}}
, we will find a pitfall at this time, then it has been provedObject.assign()
Only implements a shallow copy of the object
Object.assign()
Another thing to note is that non-enumerable objects with attributes on the prototype chain cannot be copied. Take a look at the code. :
var x = { a: 1, }; var y = Object.create(x, { b: { value: 2, }, c: { value: 3, enumerable: true, }, }); var z = Object.assign({}, y); console.log(z); //{c:3}
is surprising to get the value of z
, because x
is the prototype chain of y
, so x
Will not be copied
Attributeb
is a non-enumerable property and will not be copied
Only c
has an enumerable description, he can be Enumeration, so it can be copied
The above pitfalls can also be solved very well, and look down:
Deep copyJSON.parse(JSON.stringify())
Solution to the pitfalls of shallow copy
var x = { a: 1, b: 2, c: { d: 3, }, }; y = JSON.parse(JSON.stringify(x)); x.a = 5; x.c.d = 10; console.log(x); //{a:5, b:2, c:{d:10}} console.log(y); //{a:1, b:2, c:{d:3}}
Of course, for ordinary objects, this copying method is basically perfect, so where is its pitfall
var x = { a: 1, b: function b() { return "2"; }, }; y = JSON.parse(JSON.stringify(x)); z = Object.assign({}, x); console.log(y); //{a:1} console.log(z); //{a:1, b:function b(){return '2'}}
From the results, Object.assign()
can copy the method, JSON.parse(JSON.stringify())
cannot
Let’s look at the second one A pitfall:
var x = { a: 1, b: { c: 2, d: 3, }, }; x.c = x.b; x.d = x.a; x.b.c = x.c; x.b.d = x.d; var y = JSON.parse(JSON.stringify(x)); console.log(x); /* Uncaught TypeError: Converting circular structure to JSON at JSON.stringify (<anonymous>) at <anonymous>:8:25 */
reported an error, and the result shows that JSON.parse(JSON.stringify()),
cannot copy the circular reference object
Let’s take a look Object.assign()
var x = { a: 1, b: { c: 2, d: 3, }, }; x.c = x.b; x.d = x.a; x.b.c = x.c; x.b.d = x.d; var y = Object.assign({}, x); console.log(x); /* [object Object]{ a:1, b:[object, Object], d:[object, Object], d:1 } */
Use the expansion operator [... ]
The expansion operator for object literals is currently ECMAScript
's Phase 3 proposal makes copying objects simpler
var x = [ "a", "b", "c", "d", { e: 1, }, ]; var y = [...x]; console.log(y); //['a', 'b', 'c', 'd', {'e':1}] var m = { a: 1, b: 2, c: ["d", "e"], }; var n = { ...m, }; console.log(n); //{a:1, b:2, c:['d', 'e']}
It should be noted that the spread operator is also a shallow copy. So is it really so difficult to copy objects?
Invent your own wheel:
function copy(x) { var y = {}; for (m in x) { y[m] = x[m]; } return y; } var o = { a: 1, b: 2, c: { d: 3, e: 4, }, }; var p = copy(o);
Some people say that there shouldn’t be much problem if you do this. Then we can only laugh and keep going
var x = {}; Object.defineProperty(x, "m", { value: 5, writable: false, }); console.log(x.m); //5 x.m = 25; //这一步没报错,但是也没执行 console.log(x.m); //5
In this way, the expansion operator will also encounter pitfalls when copying objects here.
There are pitfalls everywhere, and it’s hard to guard against them.... As I write this, I guess there are still many pitfalls that haven’t been fully listed.
I’ll write more later
[End]
Recommended learning: JavaScript video tutorial
The above is the detailed content of In-depth analysis of object copy methods in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
