为什么构造函数只能返回一个对象?
如果有一个像
function a() {}
then
(new a) instanceof a === true
这样的构造函数但另一方面,
function a() { return {} }
结果是
(new a) instanceof a === false
所以我在想的是,这
function a() { return 123 }
会导致同样的结果。但是,当返回一个 Number 时,
(new a) instanceof a === true
这怎么可能呢?为什么我不能让构造函数返回对象以外的东西?
(我确实知道让构造函数返回数字是相当无用的,但我想了解这种行为的“原因”)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据规范:如果调用构造函数返回一个对象,则该对象是 new 表达式的结果。如果构造函数不返回对象(而是
undefined
或其他一些原始值),则结果是新创建的对象。如果允许基元,那么所有构造函数都必须显式返回某些内容(通常为“
this
”),否则结果将是未定义
(因为函数的结果没有返回
是未定义
)。那将是一个不必要的麻烦。此外,可以依赖
new
来始终返回一个对象,这是有道理的。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 (butundefined
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 beundefined
(because the result of a function without areturn
isundefined
). That would be a needless hassle.Additionally, it makes sense that
new
can be relied on to always return an object.