为什么构造函数只返回一个对象? [英] Why can a constructor only return an object?

查看:164
本文介绍了为什么构造函数只返回一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一个构造函数如

  function a(){} 



然后

 (new a)instanceof a = == true 






但另一方面, / p>

  function a(){return {}} 

会导致

 (new a)instanceof a === false 






所以我想的是

  function a(){return 123} 

会导致同样的事情。但是,当返回一个数字时,

 (new a)instanceof a === true 






如何实现?为什么我不能让一个构造函数返回一个对象以外的东西?



(我知道让构造函数返回一个数字是没用的,但我想了解'为什么'这个行为)

解决方案

根据规范:如果调用构造函数返回一个对象, new 表达式的结果。如果构造函数没有返回一个对象(但 undefined 或一些其他原始值),结果就是新创建的对象。



如果允许原语,那么所有构造函数都必须显式返回一些东西(通常是 this ),否则结果将是 undefined (因为没有 return 的函数的结果是 undefined )。这将是一个不必要的麻烦。



此外,有理由的是, new 可以依赖于总是返回对象。


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)

解决方案

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.

这篇关于为什么构造函数只返回一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆