javascript - 构造函数可以返回什么值来避免返回 this?

标签 javascript constructor new-operator

当使用 new 调用构造函数时,Javascript 中的 return 语句在什么情况下可以返回 this 以外的值> 关键字?

例子:

function Foo () {
  return something;
}

var foo = new Foo ();

如果我没记错的话,如果something 是一个非函数原语,this 将被返回。否则返回 something。这是正确的吗?

换句话说,something 可以取什么值来导致 (new Foo () instanceof Foo) === false

最佳答案

[[Construct]] 中描述了确切的条件 new 使用的内部属性运算符(operator):

来自 ECMA-262 3rd。版本说明:

13.2.2 [[Construct]]

When the [[Construct]] property for a Function object F is called, the following steps are taken:

  1. Create a new native ECMAScript object.
  2. Set the [[Class]] property of Result(1) to "Object".
  3. Get the value of the prototype property of F.
  4. If Result(3) is an object, set the [[Prototype]] property of Result(1) to Result(3).
  5. If Result(3) is not an object, set the [[Prototype]] property of Result(1) to the original Object prototype object as described in 15.2.3.1.
  6. Invoke the [[Call]] property of F, providing Result(1) as the this value and providing the argument list passed into [[Construct]] as the argument values.
  7. If <a href="http://bclary.com/2004/11/07/#a-8" rel="noreferrer noopener nofollow">Type</a>(Result(6)) is Object then return Result(6).
  8. Return Result(1).

看第7步和第8步,只有当 Result(6) 的类型(从 F 构造函数返回的值 函数)不是对象。

关于javascript - 构造函数可以返回什么值来避免返回 this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1978049/

相关文章:

javascript - 在 jQuery 中使用 'data-attribute' 而不是 $.data 有什么优势?

javascript - 如何在 5 秒后触发输入提示?

JAVA,setter 没有将发送到我的构造函数程序的值返回零

c++ - operator new 在内存不足时不返回 0

c++ - "new"没有在类中调用指定的构造函数?

c++ - 如何在 C++ 中重新分配?

javascript - Wami录音机,未调用回调函数

javascript - 如何将图像添加到谷歌地图 v3 中标记的信息窗口?

java - 为什么 Java 构造函数不能同步?

c++ - 复制构造函数不是深度复制,错误返回数组为空