How does “new new something” produce reliable results in JavaScript?

I am currently developing a JavaScript parser and studying the ECMAScript 5.1 specification . This is the question that puzzles me at the moment.

§ 11.2. Left expressions define the following NewExpression production:

 NewExpression : MemberExpression new NewExpression 

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

 new new Something 

(In fact, any number of new s.)

It completely puzzles me. How can new Something potential return everything that you could once again new ? Is it possible at all?

+5
source share
3 answers

This is not often, but it is possible; function returning function:

 function baz(){} function foo(){return baz} new new foo() instanceof baz // true 
+6
source

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 returns the result.

Functions are objects, so if you return a function from a function and try to instantiate the last function using new , you will return the old function, not the new object. But functions are also constructors, so you can new return a function.

 function bar() {} function foo() { return baz; } new foo === bar; // true 
+2
source

I had to use new new when using an object as a namespace. Although it will be better:

Instead:

 var Namespace = function() { var ClassFirst = this.ClassFirst = function() { this.abc = 123; } var ClassSecond = this.ClassSecond = function() { console.log("Cluttered way to access another class in namespace: ", new new Namespace().ClassFirst().abc); console.log("Nicer way to access a class in same namespace: ", new ClassFirst().abc); } } new new Namespace().ClassSecond() 

Do it:

 var Namespace = new function() { var ClassFirst = this.ClassFirst = function() { this.abc = 123; } var ClassSecond = this.ClassSecond = function() { console.log("Cluttered way to access another class in namespace: ", new Namespace.ClassFirst().abc); console.log("Nicer way to access a class in same namespace: ", new ClassFirst().abc); } } new Namespace.ClassSecond() 

Not directly related to the question, but I was googling new new javascript because it looked pretty ugly and wrong. This post may help to avoid creating an unnecessary object for other new new Google'ers.

+1
source

Source: https://habr.com/ru/post/1206293/


All Articles