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

function f1() {

    this.age = 10;

    return [];

}

var p3=new f1();

console.log(p3);//[]

console.log(p3.age);//undefined

function f2() {

    this.age = 10;

    return 20;

        }

var p2=new f2();

console.log(p2);//f2{age:10} 为什么不是20,而是一个对象?跟上一个代码有什么区别,难道因为[]是对象的原因吗?

console.log(p2.age);//10


冉冉说
浏览 728回答 1
1回答

喵喵时光机

简单的回答你的注解中已经说明了。根据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:Let obj be a newly created native ECMAScript object.Set all the internal methods of obj as specified in 8.12.Set the [[Class]] internal property of obj to "Object".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".If Type(proto) is Object, set the [[Prototype]] internal property of obj to proto.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.If Type(result) is Object then return result.Return obj.过程的说明是说,一开始构造函数会先建立一个新对象,各项准备工夫,然后呼叫(调用)函数中的代码,进行对象初始化的工作,最后回传这个对象。但是要注意第8步,说明如下:第7步时,会呼叫(调用)函数,得到return的值,称为result。第8步时,如果result是个对象时,就直接回传result。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript