Home >Web Front-end >JS Tutorial >How to Effectively Clone JavaScript Objects in Different Environments?
Cloning an object in JavaScript involves creating a copy that is independent of the original object. Modifications made to the clone should not affect the original, and vice versa.
ES2022 introduced structuredClone(), providing an efficient and standard way to clone objects. It supports cloning complex data structures, including circular references.
const clone = structuredClone(object);
For browsers that do not support structuredClone(), a manual cloning process is required. While simple objects can be cloned with a simple assignment, complex objects with non-enumerable properties or prototype inheritance require a more rigorous approach:
function clone(obj) { // Handle null, undefined, and simple types if (obj === null || typeof obj !== "object") return obj; // Clone custom Date objects if (obj instanceof Date) { return new Date(obj.getTime()); } // Clone Arrays if (obj instanceof Array) { return obj.map(clone); } // Clone Objects if (obj instanceof Object) { let clone = {}; for (const key in obj) { if (obj.hasOwnProperty(key)) { clone[key] = clone(obj[key]); } } return clone; } throw new Error("Unable to clone object. Its type is not supported."); }
This function handles special cases for Date and Array objects, ensures proper copying of custom properties, and skips prototype properties to prevent unwanted attributes from being cloned.
While this manual cloning approach is more complex, it provides greater flexibility and supports more data types compared to a simple assignment. It's important to note that it assumes a data structure without circular references, as infinite recursion can occur when cloning such structures.
The above is the detailed content of How to Effectively Clone JavaScript Objects in Different Environments?. For more information, please follow other related articles on the PHP Chinese website!