返回数组的函数上的 Javascript `new` 关键字
我正在尝试使用 new
关键字,但找不到此行为的解释。 假设我们有一个返回整数的函数:(
在 firebug 中)
>>> function x() { return 2; }
>>> x()
2
>>> new x()
x { }
但是如果该函数返回一个数组:
>>> function y() { return [2]; }
>>> y()
[2]
>>> new y()
[2]
为什么会这样?
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:
(In firebug)
>>> 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]
Why is that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
new 运算符有一个有趣的行为:它返回该运算符创建的对象,除非构造函数返回不同的对象。构造函数的任何非对象返回值都会被忽略,这就是为什么当您返回
2
时您看不到它。当您说
new x()
时,会发生以下情况:x
并将this
设置为新对象。x
不会返回任何内容,new
表达式的结果是在步骤 1 中创建的新对象。但是,如果x
返回一个非null
对象引用,那么该对象引用就是new
表达式的结果与步骤 1 中创建的对象不同。任何其他类型的返回值(null
、原始数字、原始字符串、未定义
等)被忽略;它必须是非null
对象引用,才能优先于创建的new
对象。new
运算符对对象引用进行的这种特殊处理使您可以用不同的对象替换所创建的new
对象。这在某些有限的情况下会很方便,但绝大多数大多数情况下,设计为与new
一起使用的函数(称为构造函数 >) 根本不应该返回任何内容。对于一些轻松阅读(哈!),第 13.2 节对此进行了介绍。 2(“[[Construct]]”)规范 (HTML; PDF ),由 部分引用11.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 return2
you don't see this.Here's what happens when you say
new x()
:x.prototype
.x
withthis
set to the new object.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 onenew
created. This can be handy in some limited situations, but the vast majority of the time, a function designed to be used withnew
(called a constructor function) shouldn't return anything at all.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").因为数组是一个对象,但
2
不是。如果您使用 new 关键字调用函数,它必须返回一个对象。如果您没有明确执行此操作,它会自动返回
this
(这是一个继承自funcName.prototype 的空对象)
。Because an array is an object but
2
is not.If you call a function with the
new
keyword, it has to return an object. If you don't do that explicitly, it automatically returnsthis
(which is an empty object that inherits fromfuncName.prototype)
.