Why can a constructor only return an object?

后端 未结 1 1497
粉色の甜心
粉色の甜心 2020-12-07 02:45

If there is a constructor like

function a() {}

then

(new a) instanceof a === true

But on the other

相关标签:
1条回答
  • 2020-12-07 03:31

    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.

    0 讨论(0)
提交回复
热议问题