Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can "new new Something" produce valid results in JavaScript?

I'm currently developing a JavaScript parser and study the ECMAScript 5.1 specification. Here's a question which puzzles me at the moment.

§ 11.2 Left-Hand-Side Expressions defines the following NewExpression production:

NewExpression :
    MemberExpression
    new NewExpression

If I read it correctly, then the NewExpression may be something like

new new Something

(Actually, any amount of news.)

This puzzles me completely. How could new Something potentialy return anything you could once again new? Is it possible at all?

like image 929
lexicore Avatar asked Nov 05 '14 21:11

lexicore


2 Answers

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
like image 195
elclanrs Avatar answered Oct 14 '22 22:10

elclanrs


Take a look at section 13.2.2 [[Construct]] in the specification. More precisely, step 9 of the algorithm.

  1. 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
like image 27
Ionuț G. Stan Avatar answered Oct 15 '22 00:10

Ionuț G. Stan