javascript - What is the common way to instantiate objects in Node.js? -


the following node snippiest node.js tests , know why 1 way instantiate object preferred on other?

// 1 var events = require('events'); var emitter = new events.eventemitter(); emitter.on('test', dosomething);  // 2 var net = require('net'); var server = net.createserver(); server.on('connection', dosomething);  // 3 var net = require('http'); var server = http.server(function(req, res) {   req.on('end', function() { ... }); }); 

and i'm working on node.js module , trying find common way these kind of apis.

#1 , #3 same, http.server can used factory because of first line in it:

if (!(this instanceof server)) return new server(requestlistener); 

#2 useful in top-level api functions makes chaining simpler:

require('http').createserver(handler).listen(8080); 

instead of

(new require('http').server(handler)).listen(8080); 

it's common core api modules expose both constructor , factory helper, server , createserver, , allow constructor used without new.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -