Object.Assign Putting Two And Two Together


The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Objects are a core part of JavaScript; Object.assign is a new ES6 method. Today, we’re going to discuss what it does, and techniques we can use with it, to do awesome things!

What It Does

Object.assign() wires up a source object with the properties of one or more objects. These properties are only the ones on the current object — not it’s prototype. Considering an object can have properties from functions to strings, there are cool techniques we can use with this method.


Copying Class Properties Over Through Composition

You can copy an instance of a class over to an object or a new class. The new instance is not a reference to the old object/class. This is an extremely powerful tool that embraces composition. You can use this to create new classes out of multiple objects or extend a class with an object.


Simple Assignment Of A Class’s Properties

Note that if you inherit from a class created through a function, you can pass the methods over through simple assignment if they’re static (attached to the class itself). You can also do this with a class created from an object.

Example 2

Appending To An Existing Class/Object

Since Object.assign() copies properties over, all new properties are appended to the source object/class. Meaning, we can extend the functionality. Careful, because we can overwrite properties with the same name. Another thing: we can create an object within the assignment statement to have more control over the appending of properties.



Hope this information helps you improve your code! Object.assign() makes wiring objects together a lot easier. Use it to leverage your objects and practice composition.

Until next time!




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s