Šime Vidas
Šime Vidas

Reputation: 185913

Legitimate uses of Object(o)

When an object value is provided to the Object constructor, that value will be returned unchanged. So, given an object obj:

obj === new Object( obj )

and

obj === Object( obj )

Then, what's the point of doing Object( obj ) in the first place? I can understand doing Object( 'foo' ), or Object( 123 ) - it creates a wrapper object for the primitive value, but if we already have an object obj, why would we do Object( obj )?

Is this pattern useless?

Upvotes: 4

Views: 159

Answers (2)

Bergi
Bergi

Reputation: 664425

The comparison will check whether obj is a real object. It is nearly equivalent to checking for

typeof obj == "object"

Yet, that is also true for null and can lead to strange errors when we try to access its properties. So, instead of writing if (typeof obj == "object" && obj !== null) it is commonly shortened to if (obj === Object(obj)).

Also, it yields true for function objects as well, while the typeof test does not - but sometimes you want to allow everything that can hold properties, and someone will get angry on your lib if you forget functions.

So much about the pattern, Reid has written an excellent answer about the internals of Object, which explains the behaviour you already described in your question.

Upvotes: 4

Reid
Reid

Reputation: 19409

Assuming that obj is an Object value, it will have no effect. Let's look at the specification for ES5 (yay!).

According to § 15.2.1.1 Object([value]), if obj is not null or undefined, then we return ToObject(value).

Now we turn our attention to § 9.9 ToObject. It says that if the argument is of type Object, "the result is the input argument (no conversion)."

Hence, there is no theoretical reason to use Object(obj) where you know obj is an Object: it is the exact same as writing obj.

The other case you listed was new Object(obj), which depends on § 15.2.2.1 new Object([value]). It says that if value is supplied and the type of value is an Object, return obj if obj is a native ECMAScript object. If it is not native, then the result is implementation-defined (and therefore browser-dependent and not recommended to use, in my opinion).

Upvotes: 2

Related Questions