javascript - Using factory methods as alternative to passing anonymous functions -
i watching video on node.js , saw speaker say, prefers instead of using anonymous call backs:
var server = server.createserver(server.createreq(req,res));
i think nice named function parameters can passed instead of anonymous function closure.
question 1: implementation of createreq returns anonymous function, wouldn't it?
how better? can see being better because unlike closure @ createserver
level, closure @ createreq
level more contained - not store reference other unnecessary variables (non req,res).
and speaker said, guess visualize realtionships better between different parts of code.
question 2: there other benefits?
a reason why might want call function returns function may starting multiple servers within same process, , want them share same request handler.
another thing keep in mind each anonymous function must allocated on heap, , incurs garbage collection overhead. using named function instead of anonymous function, can reduce cost.
for example, maybe untested , incomplete example:
var server = server.createserver(handlerequest); function handlerequest(req, res) { new client(req, res); } function client(req, res) { this.req = req; this.res = res; this.body = ""; req.on("data", function (chunk) { self.ondata(chunk); }); } client.prototype.ondata = function (chunk) { this.body += chunk.tostring(); };
this example uses small anonymous function bind data
event callbacks specific instance of client, other functions named.
Comments
Post a Comment