JavaScript:使用没有运算符“new"的构造函数 [英] JavaScript: using constructor without operator '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>
第一行没有 new
操作符.
In the first line there is no new
operator.
据我所知,JavaScript 中的构造函数是一个函数,它初始化由运算符 new
并且它们不打算返回任何内容.
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.
推荐答案
一般来说,如果某物被记录为构造函数,则将 new
与它一起使用.但在这种情况下,RegExp
为您将其作为函数调用的情况定义了工厂"行为.请参阅 ECMAScript (JavaScript) 规范(链接到即将发布的规范;新规范中的部分编号相同,您可以从 ECMA front 下载页面 [在右侧];我不想直接链接到大约 4MB 的 PDF 文件):
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):
15.10.3 作为函数调用的 RegExp 构造函数
15.10.3.1 RegExp(pattern, flags)
如果 pattern 是一个对象 R,其 [[Class]] 属性为 "RegExp" 并且标志未定义,则返回 R 不变.否则调用 RegExp 构造函数 (15.10.4.1),将模式和标志参数传递给它,并返回由该构造函数构造的对象.
15.10.3 The RegExp Constructor Called as a Function
15.10.3.1 RegExp(pattern, flags)
If pattern is an object R whose [[Class]] property is "RegExp" and flags is undefined, then return R unchanged. Otherwise call the RegExp constructor (15.10.4.1), passing it the pattern and flags arguments and return the object constructed by that constructor.
您实际上可以定义自己的 JavaScript 构造函数以允许省略 new
关键字(通过检测它们已被作为函数调用,然后正确调用自己),但我不会不要建议它,因为它会导致误导性代码.
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.
这篇关于JavaScript:使用没有运算符“new"的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!