How to Clone Objects with Object.create in Javascript
By Tan Lee Published on Feb 08, 2025 135
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.
- How to use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript