Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...