Why can a constructor only return an object?

空扰寡人 提交于 2019-11-26 22:04:10

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/6775486/why-can-a-constructor-only-return-an-object

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