为什么构造函数只能返回一个对象? [英] Why can a constructor only return an object?
问题描述
如果有类似的构造函数
function a() {}
然后
(new a) instanceof a === true
<小时>
但另一方面,
But on the other hand,
function a() { return {} }
结果
(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)
推荐答案
根据规范:如果调用构造函数返回一个对象,则该对象是 new
表达式的结果.如果构造函数没有返回对象(但是undefined
或其他一些原始值),则结果是新创建的对象.
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.
如果允许基元,那么所有构造函数都必须显式返回一些东西(通常是this
"),否则结果将是undefined
(因为没有 return
的函数是 undefined
).那将是一个不必要的麻烦.
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.
此外,可以依赖 new
来始终返回一个对象.
Additionally, it makes sense that new
can be relied on to always return an object.
这篇关于为什么构造函数只能返回一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!