Question 47
Question
How would you create a shallow copy of an object using prototypes?
Answer
Here's how you can create a shallow copy of an object in JavaScript, leveraging prototypes:
Explanation:
Object.create(Object.getPrototypeOf(obj))
:Object.getPrototypeOf(obj)
retrieves the prototype of the original object.Object.create()
creates a new object with this retrieved prototype. This ensures that the newly copied object inherits from the same prototype chain as the original object, meaning its methods will likely be identical.
Iterating and Copying Properties:
The
for...in
loop iterates over each property in the original object.Object.prototype.hasOwnProperty.call(obj, key)
checks if a property belongs to the original object itself (and not inherited from its prototype). This is important because we only want to copy properties directly owned by the original object.
newObj[key] = obj[key]
:Each property of the original object is copied to the new object (
newObj
).
Important Notes about Shallow Copies:
Nested Objects: A shallow copy will only create a reference to nested objects within the original object. Changes to nested objects in the copy will affect the original object, as they share the same references.
Arrays: Shallow copies of arrays also maintain references to their elements. Modifications to elements within the copied array will affect the original array.
Last updated