javascript - 创建实例的构造函数中return 不同类型的值(对象),为什么会导致实例属性输出也不同?
伊谢尔伦
伊谢尔伦 2017-04-10 18:10:15
[JavaScript讨论组]
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
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(2)
巴扎黑

简单的回答

你的注解中已经说明了。

根据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。

大家讲道理

当你return 一个对象的时候,得到的就是你return的这个对象;
当你没有return或者return的值不是一个对象时,返回构造的Object
权威指南应该说过这方面..

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号