Legitimate uses of Object(o)

筅森魡賤 提交于 2019-11-28 01:23:39

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.

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!