JavaScript: Object Construct with object parameter

Viewed 80

I have seen some code with something like the following:

var thing=Object(stuff);    //  stuff is an object

where stuff is an object.

(I have seen this sort of code on Mozilla’s web site in a polyfill for Object.assign).

The documentation on Mozilla is not specific about what it means if the parameter is an object.

As far as I can tell, the new object is a reference to the original object. I thought that you would get the same if you simply wrote:

var thing=stuff;    //  stuff is an object

What is the difference between the two?

Edit

Do I need to say it? This is not a question about Object.assign. It’s a question about using the Object constructor.

2 Answers

difference between literal and Object() -

The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

When called in a non-constructor context, Object behaves identically to new Object(). - from MDN

If you use Object, you can insert any value and get new object, but if you use object as argument of Object -you get link to this object. if stuff is object , var thing=Object(stuff); and var thing=stuff; are equivalent, else if stuf for example is number :

var thing=Object(stuff); ---object;

var thing=stuff; ---number;

The polyfill for Object.assign allows us to merge multiple objects at a time. Your point on creating a new Object is true but there are difference use cases.

Consider we have 3 objects and we want to merge them:

const a = { 'key1': 'value1' };
const b = { 'key2': 'value2', 'key3': 'this will get replaced' };
const c = { 'key3': 'value3' };

// Using Object.assign
const abc = Object.assign(a, b, c);
// abc will have the value {key1: "value1", key2: "value2", key3: "value3"}
Related