JavaScript的`在函数返回数组new`关键字 [英] Javascript `new` keyword on function returning array
问题描述
我是用新
关键字试验和我找不到此行为的解释。
比方说,我们有一个函数返回一个整数:
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()
:
- 的跨preTER创建一个新的空白对象。
- 它设置对象的基础原型
x.prototype
。 - 它调用
X
与这个
设置为新的对象。 - 在正常情况下,
X
不返回任何东西和新
前$ P $的结果pssion是在步骤1中的创建新的对象,但,如果X
返回一个非 -空
的对象引用的,则该对象的引用是新
前pression的结果,而不是对象在步骤1中创建的任何其他类型的返回值(空
,原始数字,字符串原始,未定义
等)被忽略;它是一个非 -空
对象引用采取precedence在对象新
创建
- The interpreter creates a new blank object.
- It sets the object's underlying prototype to
x.prototype
. - It calls
x
withthis
set to the new object. - In the normal case,
x
doesn't return anything and the result of thenew
expression is the new object created in step 1. But, ifx
returns a non-null
object reference, then that object reference is the result of thenew
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 objectnew
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屋!