How can "new new Something" produce valid results in JavaScript?
It is not common at all, but it is possible; a function that returns a function:
function baz(){}
function foo(){return baz}
new new foo() instanceof baz // true
Take a look at section 13.2.2 [[Construct]] in the specification. More precisely, step 9 of the algorithm.
- If Type(result) is Object then return result.
Functions are objects, so if you return a function from a function and try to instantiate the latter function using new
, you'll get back the former function, not a new object. But functions are also constructors, so you can new
the returned function.
function bar() {}
function foo() { return bar; }
new foo === bar; // true