ghasemkiani avatar

JavaScript Basics: Object.assign

ghasemkiani

Published: 29 Jan 2018 › Updated: 29 Jan 2018JavaScript Basics: Object.assign

JavaScript Basics: Object.assign

The function Object.assign is used to assign the values of “enumerable” and “own” properties from one or more source objects to a target object (first argument). If the properties have getters or setters, they will be invoked. This is what the word “assign” means, so it's not just copying values from an object to another.

Here is an example:

    class Test {
        constructor(arg) {
            Object.assign(this, arg);
        }
    }

In fact, this is my favorite use case for this operation. The above code gives you the power to assign any properties of the newly created object in the constructor.

Remember that the function can accept multiple source objects as further arguments. This function overwrites any values that already exist in the target object.


Related Posts

Leave JavaScript Basics: Object.assign to:

Written by

Read more #javascript posts


Best Posts From ghasemkiani

We have not curated any of ghasemkiani's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From ghasemkiani