How to Clone Objects with Object.create in Javascript
By FoxLearn 2/8/2025 2:57:42 AM 20
What is Object.create?
Object.create
is a method that allows you to create a new object based on an existing object. When you use Object.create
, it generates an empty object and links its prototype (__proto__
) to the object you want to clone. This creates a prototype chain, allowing the new object to inherit properties and methods from the original object.
Steps to Clone an Object Using Object.create
:
1. Creating the source object that you want to clone.
var carDetails = { brand: "Toyota", model: "Camry", year: 2022, color: "Black" };
2. Use Object.create
to create a new object, passing the original object as the prototype.
var newCarObject = Object.create(carDetails);
In this example, we’re creating a new object newCarObject
based on the carDetails
object using Object.create
. When we inspect newCarObject
in the debugger, we will notice that it is an empty object, but it has an internal __proto__
property pointing to carDetails
, thus inheriting its properties.
While debugging, you will see that newCarObject
doesn't directly have the properties brand
, model
, year
, or color
. Instead, they exist in the prototype chain, making them accessible to the new object.
Object.create
is a great way to clone an object when you only need a shallow copy that inherits from the original object.