Chiu Chiu - 3 months ago 10
Javascript Question

What's new() in node.js

I'm studying the WebRTC tutorial from Google's codelab.

In its

index.js
section for Node.js. I has the following line.

var fileServer = new(nodeStatic.Server)();


I understand
new
is an operator to create instances. But it above is using
new(nodeStatic.Server)()
which confuses me.

Can someone please explain it for me? Thanks.

Answer

nodeStatic.Server is apparently a constructor. So, your code works like this;

let serverConstructor = nodeStatic.Server;
let fileServer = new serverConstructor();

The parens are used in your original code to control the competing precedence between new, () and the . operator to make sure things are evaluated in the proper order. You'd have to study the precedence rules in the Javascript spec to see if the parens around nodeStatic.Server are actually needed or not.

Comments