JavaScript的`在函数返回数组new`关键字 [英] Javascript `new` keyword on function returning array

查看:105
本文介绍了JavaScript的`在函数返回数组new`关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是用关键字试验和我找不到此行为的解释。
比方说,我们有一个函数返回一个整数:

I was experimenting with the new keyword and I can't find an explanation for this behavior. Let's say we have a function returning an integer:

(萤火虫)

>>> function x() { return 2; }
>>> x()
2
>>> new x()
x { }

但如果该函数返回一个数组:

But if the function returns an array :

>>> function y() { return [2]; }
>>> y()
[2]
>>> new y()
[2]

这是为什么?

推荐答案

运营商有一个有趣的现象:它返回由操作员,除非构造函数创建的对象返回不同的对象。构造函数中的任何非对象返回值被忽略,这就是为什么当您返回 2 你没有看到这一点。

The new operator has an interesting behavior: It returns the object created by the operator unless the constructor function returns a different object. Any non-object return value of the constructor function is ignored, which is why when you return 2 you don't see this.

下面是当你说新的x()会发生什么:

Here's what happens when you say new x():


  1. 的跨preTER创建一个新的空白对象。

  2. 它设置对象的基础原型 x.prototype

  3. 它调用 X 这个设置为新的对象。

  4. 在正常情况下, X 不返回任何东西和前$ P $的结果pssion是在步骤1中的创建新的对象,但,如果 X 返回一个非 - 对象引用的,则该对象的引用是前pression的结果,而不是对象在步骤1中创建的任何其他类型的返回值(,原始数字,字符串原始,未定义等)被忽略;它是一个非 - 对象引用采取precedence在对象创建

  1. The interpreter creates a new blank object.
  2. It sets the object's underlying prototype to x.prototype.
  3. It calls x with this set to the new object.
  4. In the normal case, x doesn't return anything and the result of the new expression is the new object created in step 1. But, if x returns a non-null object reference, then that object reference is the result of the new expression rather than the object created in step 1. Any other kind of return value (null, primitive numbers, primitive strings, undefined, etc.) is ignored; it has to be a non-null object reference to take precedence over the object new created.

给对象由运营商引用让你替换一个不同的对象之一这种特殊的处理创建。这可能是在某些有限的情况下派上用场,但是的广大的大部分时间,要与(称为构造函数的)不应该返回任何东西。

This special treatment given to object references by the new operator lets you substitute a different object for the one new created. This can be handy in some limited situations, but the vast majority of the time, a function designed to be used with new (called a constructor function) shouldn't return anything at all.

对于一些轻读(哈!),这是由覆盖第13.2.2节(的[[建设]的)的规范(的 HTML ; PDF ) ,这是由节中引用11.2.2 运算符的)。

For some light reading (hah!), this is covered by Section 13.2.2 ("[[Construct]]") of the specification (HTML; PDF), which is referenced by Section 11.2.2 ("The new operator").

这篇关于JavaScript的`在函数返回数组new`关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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