JavaScript:使用不带运算符“new”的构造函数
请帮助我理解为什么以下代码有效:
<script>
var re = RegExp('\\ba\\b') ;
alert(re.test('a')) ;
alert(re.test('ab')) ;
</script>
在第一行中没有 new
运算符。
据我所知, JavaScript 中的构造函数是一个初始化由运算符 < 创建的对象的函数code>new 并且它们并不意味着返回任何内容。
Please help me to understand why the following code works:
<script>
var re = RegExp('\\ba\\b') ;
alert(re.test('a')) ;
alert(re.test('ab')) ;
</script>
In the first line there is no new
operator.
As far as I know, a contructor in JavaScript is a function that initialize objects created by the operator new
and they are not meant to return anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,如果某个东西被记录为构造函数,请对其使用
new
。但在本例中,RegExp
对于您将其作为函数调用的情况具有定义的“工厂”行为。请参阅 ECMAScript (JavaScript) 规范 第 15.10.3 节(链接到即将发布的规范;章节号与新规范中的相同,您可以从 ECMA 下载该规范 首页 [在右侧];我不想直接链接到 ~4MB PDF 文件):实际上,您可以定义自己的 JavaScript 构造函数以允许省略
new
关键字(通过检测它们已被作为函数调用,然后转身并正确调用自身),但我不建议因为它会导致误导性代码。 (而且你不能使用class
语法来做到这一点,你必须使用旧的、更笨重的function
语法。)In general, if something is documented as being a constructor, use
new
with it. But in this case,RegExp
has a defined "factory" behavior for the situation where you've called it as a function instead. See Section 15.10.3 of the ECMAScript (JavaScript) specification (that links to the outgoing spec; the section number is the same in the new spec, which you can download from the ECMA front page [on the right-hand side]; I don't want to directly link to a ~4MB PDF file):You can actually define your own JavaScript constructor functions to allow omitting the
new
keyword (by detecting they've been called as a function instead, and turning around and calling themselves correctly), but I wouldn't suggest it as it leads to misleading code. (And you can't do it withclass
syntax, you have to use the older, clunkierfunction
syntax.)+1 TJ Crowder 拥有它。 ECMAScript 标准不遗余力地定义内置构造函数作为普通函数调用时的行为。通常它只是将自身作为构造函数回调,但也有一些更复杂的情况。
一般来说,构造函数可以忽略
this
并仅返回一个独立的对象:在这种情况下,您同样可以使用该函数作为构造函数(使用
new
)或普通函数。如果构造函数不返回任何内容(这是构造函数的常见模式),则 new 运算符本身会确保它返回创建并作为 this 传递的新对象。在这种情况下,您必须使用
new
。最好不要依赖作为裸函数工作的构造函数,并且内置构造函数的替代行为很少有任何用处,因此通常您应该坚持使用
new
。+1 TJ Crowder has it. The ECMAScript standard goes out of its way to define behaviours for the built-in constructor functions when called as plain functions. Often it simply calls itself back as a constructor, but there are some more complicated cases.
In general, a constructor can ignore
this
and just return an independent object:in this case you can equally use the function as a constructor (with
new
) or a plain function.If the constructor doesn't return anything, as is the usual pattern for constructors, the
new
operator itself ensures that it returns the new object created and passed asthis
. In this case you must usenew
.It's best not to rely on a constructor working as a bare function, and the alternative behaviours of the built-in constructors are rarely of any use, so generally you should stick with
new
.