gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:45:14 24 4
gpt4 key购买 nike

当使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com