构造函数返回什么值可以避免返回?

编程入门 行业动态 更新时间:2024-10-23 05:01:40
本文介绍了构造函数返回什么值可以避免返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当使用 new

What are the exact circumstances for which a return statement in Javascript can return a value other than this when a constructor is invoked using the new keyword?

示例:

function Foo () { return something; } var foo = new Foo ();

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

If I'm not mistaken, if something is a non-function primitive, this will be returned. Otherwise something is returned. Is this correct?

IOW,什么值可以某事引起 ()instanceof Foo)=== false ?

IOW, what values can something take to cause (new Foo () instanceof Foo) === false?

推荐答案

code> [[Construct]] 内部属性,由 new 运算符:

The exact condition is described on the [[Construct]] internal property, which is used by the new operator:

版本规格:

13.2.2 [[Construct]]

[[Construct]] 属性函数对象 F 是调用,执行以下步骤:

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

  • 创建新的原生ECMAScript对象。
  • 设置 [[Class]] 属性结果(1)到对象。
  • 获取 F 的原型属性的值。
  • 如果 / code>是一个对象,请设置 [[Prototype ]] 属性结果(1)到结果(3) 结果(1) c> c> 15.2.3.1 。
  • 调用的属性 c> c> F ,提供结果(1)为 this 参数列表传递给 [[Construct]] 作为参数值。
  • 如果 类型(结果(6))是 对象然后返回结果(6)。
  • 结果(1)。
  • Create a new native ECMAScript object.
  • Set the [[Class]] property of Result(1) to "Object".
  • Get the value of the prototype property of F.
  • If Result(3) is an object, set the [[Prototype]] property of Result(1) to Result(3).
  • 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.
  • 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.
  • If Type(Result(6)) is Object then return Result(6).
  • Return Result(1).
  • 查看步骤7和8,只有当类型 Result(6)(从 F 构造函数函数)是不一个对象。

    Look at steps 7 and 8, the new object will be returned only if the type of Result(6) (the value returned from the F constructor function) is not an Object.

    更多推荐

    构造函数返回什么值可以避免返回?

    本文发布于:2023-11-16 11:48:42,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1604010.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:函数

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!