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.
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.
Appending To An Existing Class/Object
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 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!