为了账号安全,请及时绑定邮箱和手机立即绑定

创建实例的构造函数中return 不同类型的值(对象),为什么会导致实例属性输出也不同?

创建实例的构造函数中return 不同类型的值(对象),为什么会导致实例属性输出也不同?

冉冉说 2018-09-03 13:31:36
function f1() {    this.age = 10;    return [];}var p3=new f1();console.log(p3);//[]console.log(p3.age);//undefinedfunction f2() {    this.age = 10;    return 20;        }var p2=new f2();console.log(p2);//f2{age:10} 为什么不是20,而是一个对象?跟上一个代码有什么区别,难道因为[]是对象的原因吗?console.log(p2.age);//10
查看完整描述

1 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

简单的回答

你的注解中已经说明了。

根据ECMAScript标准的规则,如果是在构造函数中,当回传值(return)是个对象时,用new之后就是得到那个return的对象。问题中return了一个数组,数组是个对象类型,所以得到数组。

所以回传值是对象以外的如数字、字节、布林或null、undefined(没写return时是这个)时,就会回传新构造出来的实例对象。

详细的回答

以下出自: ECMAScript 13.2.2 [[Construct]]

说明了构造函数的调用过程,构造函数当然是用了new运算符的情况。


When the [[Construct]] internal method for a Function object F is called with a possibly empty list of arguments, the following steps are taken:

  1. Let obj be a newly created native ECMAScript object.

  2. Set all the internal methods of obj as specified in 8.12.

  3. Set the [[Class]] internal property of obj to "Object".

  4. Set the [[Extensible]] internal property of obj to true.
    Let proto be the value of calling the [[Get]] internal property of F with argument "prototype".

  5. If Type(proto) is Object, set the [[Prototype]] internal property of obj to proto.

  6. If Type(proto) is not Object, set the [[Prototype]] internal property of obj to the standard built-in Object prototype object as described in 15.2.4.
    7.Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.

  7. If Type(result) is Object then return result.

  8. Return obj.


过程的说明是说,一开始构造函数会先建立一个新对象,各项准备工夫,然后呼叫(调用)函数中的代码,进行对象初始化的工作,最后回传这个对象。但是要注意第8步,说明如下:

第7步时,会呼叫(调用)函数,得到return的值,称为result。
第8步时,如果result是个对象时,就直接回传result。


查看完整回答
反对 回复 2018-10-28
  • 1 回答
  • 0 关注
  • 719 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号