javascript - 为什么构造函数返回对象,而不是 JavaScript 中的原语?

标签 javascript constructor

<分区>

我试图了解 JavaScript(或至少 V8)关于构造函数的行为。

我知道,JavaScript 构造函数永远不应该返回任何东西(所以:undefined)。

但考虑一下这个 JavaScript:

function Thing() { 
  return '';
}
var t = new Thing();
console.log(t, typeof t); // => Thing {} "object"

现在,如果你这样做:

function Thing() { 
  return { hi: '' };
}
var t = new Thing();
console.log(t, typeof t); // => Object {hi: ""} "object"

甚至:

function Thing() { 
  this.a = 'a';
  return { hi: '' };
}
var t = new Thing();
console.log(t, typeof t); // => Object {hi: ""} "object"

那么,如果您编写这种代码,为什么 JavaScript 中的构造函数返回一个对象,而不是原始类型?


this SO answer 中也提到了这种行为,但没有解释。我还滚动了 The new Operator ECMAScript 规范的一部分,及其 Construct剪断了,但这并没有启发性。

有任何提示或知识(请使用通俗易懂的英语)吗?

最佳答案

这是因为,根据定义,构造函数的目的是生成对象,而不是基元:

4.3.4 constructor

function object that creates and initialises objects

因此,[[Construct]]内部方法(通过 new operator 调用),检查 [[Call]] 返回值的类型:

13.2.2 [[Construct]]

  1. 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.
  2. If Type(result) is Object then return result.
  3. Return obj.

其实这是一个invariant :

[[Construct]] ( )

  • The Type of the return value must be Object.

关于javascript - 为什么构造函数返回对象,而不是 JavaScript 中的原语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35702917/

相关文章:

javascript - 将dir rtl属性添加到vuejs中的html标签

javascript - 在vuejs中访问数组内部数组的值

c++ - 为什么 const 成员必须在构造函数初始化器中而不是在其主体中初始化?

constructor - 构造函数中的 future 不起作用

class - F#新关键字。这是为了什么

javascript - 在 ng-repeat 中使用 AngularJS 从一种状态到另一种状态进行动画处理

javascript - 为什么 Date.now() | 0 与 Date.now() 不同

java - 构造函数 Time_Class_sub(int, int, int) 未定义

java - 即使我有一个以 Object 作为参数的公共(public)构造函数,构造函数反射也不接受 Map 或 List 参数

javascript - Anime.js 与 Wordpress : module is not defined