Compose Objects with Object.assign to Create a Direct Copy

InstructorTyler Clark

Share this video with your friends

Send Tweet

Coupling objects together can create a brittle relationship. If the prototype object is mutated or replaced later in development, that can cause issues to any new implementations of 'child' objects that use those properties. Instead, let's use Object.assign to compose objects. This method creates a direct copy of all properties and does not reference the source object's properties in memory.

Ganesh Deshmukh
~ 2 years ago

If the parent object has nested properties and we create new child object using Object.assign then those nested properties will reference the source object's properties.

const parent = { hair: "brown", body: { skin: { color: "white", }, }, heightInInches() { return this.height * 12; }, };

const child = Object.assign({ height: 6 }, parent);

parent.body.skin.color = "red";

console.log(child); /// {"height":6,"hair":"brown","body":{"skin":{"color":"red"}}}