构造函数可以返回哪些值来避免返回 this? [英] What values can a constructor return to avoid returning this?

查看:29
本文介绍了构造函数可以返回哪些值来避免返回 this?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 newreturn 语句可以返回除 this 以外的值的确切情况是什么?> 关键字?

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?

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

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

推荐答案

[[Construct]] 内部属性描述了确切的条件,new 运算符:

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

来自 ECMA-262 3rd.版本规范:

From the ECMA-262 3rd. Edition Specification:

13.2.2 [[构造]]

Function 对象 F[[Construct]] 属性是调用,采取以下步骤:

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

  1. 创建一个新的原生 ECMAScript 对象.
  2. 设置[[Class]]Result(1) 的属性为 "Object".
  3. 获取F的prototype属性的值.
  4. 如果 Result(3) 是一个对象,则设置 [[Prototype]] Result(1)Result(3) 的属性.
  5. 如果 Result(3) 不是对象,则设置 [[Prototype]]Result(1)的属性转换为原始的Object原型对象作为15.2.3.1 中有所描述.
  6. 调用[[Call]]F 属性,提供 Result(1) 作为 this 值和提供传入 [[Construct]] 的参数列表作为参数值.
  7. 如果 输入(Result(6))Object 然后返回 Result(6).
  8. 返回Result(1).
  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 Type(Result(6)) is Object then return Result(6).
  8. 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.

这篇关于构造函数可以返回哪些值来避免返回 this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆