Cloning JavaScript objects is a crucial task in various programming scenarios. However, creating a copy of an object that remains unaffected by changes made to the original can be challenging due to the complexities of JavaScript's object system.
JavaScript's native object assignment operator (e.g., x = y) only creates a reference to the original object. Changes made to either x or y will affect both objects. Additionally, copying objects derived from built-in JavaScript objects (e.g., Array, Date) can introduce unwanted properties.
To create a deep copy of a JavaScript object, consider the following comprehensive solution:
function clone(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; }
This function employs a recursive approach to traverse the object's properties and create a new object with separate instances for each property value. It handles the cases of null, undefined, and various built-in object types while excluding non-enumerable and hidden properties.
While the solution covers most scenarios, it assumes that the object data forms a tree structure, meaning there are no circular references within the object. Also, it requires knowledge of the object's constructor to properly instantiate the cloned object.
In modern browsers, the structured cloning standard provides a more robust and efficient way to create deep copies of objects. The structuredClone() function clones the object in its entirety, preserving hidden properties and circular references.
const clone = structuredClone(object);
Remember, cloning objects can be a complex task, and consider the limitations of each approach based on the specific requirements of your application.
The above is the detailed content of How to Create a True Deep Copy of a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!