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
118 views
in Technique[技术] by (71.8m points)

javascript - Why can a constructor only return an object?

If there is a constructor like

function a() {}

then

(new a) instanceof a === true

But on the other hand,

function a() { return {} }

results in

(new a) instanceof a === false

So what I was thinking is that

function a() { return 123 }

would result in the same thing. However, when returning a Number,

(new a) instanceof a === true

How is this possible? Why can't I make a constructor return something else than an Object?

(I do know making a constructor returning a Number is rather useless but I would like to understand the 'why' of this behaviour)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

According to the spec: If calling the constructor returns an object, then this object is the result of the new-expression. If the constructor doesn't return an object (but undefined or some other primitive value), the result is the newly created object.

If primitives were allowed, then all constructors would have to explicitly return something (typically "this"), otherwise the result would be undefined (because the result of a function without a return is undefined). That would be a needless hassle.

Additionally, it makes sense that new can be relied on to always return an object.


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

...