Home > Web Front-end > JS Tutorial > How to Perfectly Clone JavaScript Objects?

How to Perfectly Clone JavaScript Objects?

Patricia Arquette
Release: 2024-12-26 20:50:21
Original
614 people have browsed it

How to Perfectly Clone JavaScript Objects?

How to Accurately Duplicate JavaScript Objects

JavaScript's built-in methods cannot guarantee the precise duplication of objects. This is due to the presence of prototype-derived properties and hidden attributes, which can lead to unforeseen results when cloning. To address this issue, various approaches have been developed.

2022 Update: Structured Cloning

A new JS standard called structured cloning provides a straightforward solution. It is supported by many modern browsers and allows for accurate duplication with the following syntax:

const clone = structuredClone(object);
Copy after login

Traditional Approach

In previous versions of JavaScript, a custom cloning function can be implemented using the following steps:

  1. Handling non-enumerable properties: Use the hasOwnProperty method to skip prototype properties and focus on those directly defined on the object.
  2. Cloning non-enumerable attributes: Explicitly copy hidden properties if their names are known, such as prototype or __proto__.
  3. Configuring prototype inheritance: Ensure that the copied object's prototype matches the original. This may require manually setting it or calling the source object's constructor.
  4. Handling non-enumerable data structures: Specific handling is needed for data structures with non-enumerable members, such as Date objects.
  5. Handling cyclical structures: Avoid infinite recursion by tracking visited objects and sharing references instead of deep cloning.

An example of a cloning function that addresses these challenges is provided below:

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;

    // Handing different object types
    // ... implementation for Date, Array, and Object

    // Generic fallback: deep copy properties
    var copy = {};
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
    }
    return copy;
}
Copy after login

This function assumes that the object forms a tree structure and does not contain any cyclic references. Handling cyclic structures requires a more complex approach.

The above is the detailed content of How to Perfectly Clone JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template