Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...