Alex Rivera | Logout

Why can some constructors be called without using the `new` operator?

Asked 2009-12-18T13:56:54.317
35

Please help me to understand why the following code works:

var re = RegExp('\\ba\\b') ;
console.log(re.test('a')) ;
console.log(re.test('ab')) ;

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.

Edit
Report

1 Answer

13

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

constructors in javascript [...] are not meant to return anything

In general, a constructor can ignore this and just return an independent object:

function Thing() {
    return {'foo': 1};
}

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 as this. In this case you must use new.

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.

answered 2009-12-18T14:21:06.263

Your Answer