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.
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.)